#!/bin/sh
set -e

ENV=$1

if [ -z "$CLOUDFLARE_TOKEN" ]; then
  echo "CLOUDFLARE_TOKEN is missing"
  exit 1;
fi;

if [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then
  echo "CLOUDFLARE_ACCOUNT_ID is missing"
  exit 1;
fi;

if [ -z "$SONGWHIP_WEB_PUBLIC_ENDPOINT" ]; then
  echo "SONGWHIP_WEB_PUBLIC_ENDPOINT is missing"
  exit 1;
fi;


if [ -z "$SONGWHIP_WEB_ORIGIN_ENDPOINT" ]; then
  echo "SONGWHIP_WEB_ORIGIN_ENDPOINT is missing"
  exit 1;
fi;

if [ -z "$SONGWHIP_API_ENDPOINT" ]; then
  echo "SONGWHIP_API_ENDPOINT is missing"
  exit 1;
fi;

if [ -z "$SONGWHIP_ENV" ]; then
  echo "SONGWHIP_ENV is missing"
  exit 1;
fi;

DIR="$( cd "$( dirname "$0" )" && pwd )"
WRANGLER_FILE="wrangler.tmp.toml"
WORKER_ID="songwhip-web-development"
KV_TITLE="$WORKER_ID-kv"
KV_ID=

# Get the KV ID currently bound to the worker
echo "Getting currently bound KV" >&2
PREV_KV_ID=$($DIR/getKvIdByTitle $KV_TITLE)

if [ "$PREV_KV_ID" != '' ]; then
  echo "existing development kv found ($PREV_KV_ID)" >&2
  KV_ID=$PREV_KV_ID;
else
  echo "no development kv instance found"

  # Create a new KV namespace
  echo "create new kv" >&2
  KV_ID=$($DIR/createKv $KV_TITLE)
  echo "new kv id: $KV_ID" >&2
fi

echo "name = \"$WORKER_ID\"
main = \"dist/worker.js\"
compatibility_date = \"2022-09-05\"

kv_namespaces = [
  { binding = \"KV_PAGES\", id = \"${KV_ID}\", preview_id = \"${KV_ID}\" },
]

[build]
command = \"yarn build\"
watch_dir = \".\"" > $WRANGLER_FILE

echo "deploy the worker"

# clear the local wrangler cache which stores the account-id
# meaning we get permission errors when changing account
rm -rf node_modules/.cache/wrangler

CLOUDFLARE_KV_ID=$KV_ID \
CLOUDFLARE_ACCOUNT_ID=$CLOUDFLARE_ACCOUNT_ID \
CLOUDFLARE_API_TOKEN=$CLOUDFLARE_TOKEN \
wrangler dev --config $WRANGLER_FILE --local

rm $WRANGLER_FILE
