#!/bin/bash
set -e
CDIR="/home/rurouni/Unspooled/services/addon-config-worker"
TOK=*** /tmp/cf_token)

echo "=== Deploying config worker ==="
cd "$CDIR"
CLOUDFLARE_API_TOKEN="$TOK" npx wrangler deploy 2>&1 || {
  echo "Config failed, deleting and retrying..."
  curl -s -X DELETE "https://api.cloudflare.com/client/v4/accounts/274c094edb3fe89140e277525c9c5577/workers/scripts/addon-config-worker" \
    -H "Authorization: Bearer ***
  CLOUDFLARE_API_TOKEN="$TOK" npx wrangler deploy 2>&1
}

echo ""
echo "=== Deploying auth worker ==="
cd "$CDIR"
CLOUDFLARE_API_TOKEN="$TOK" npx wrangler deploy --config auth_wrangler.toml 2>&1 || {
  echo "Auth failed, deleting and retrying..."
  curl -s -X DELETE "https://api.cloudflare.com/client/v4/accounts/274c094edb3fe89140e277525c9c5577/workers/scripts/addon-auth-worker" \
    -H "Authorization: Bearer ***
  CLOUDFLARE_API_TOKEN="$TOK" npx wrangler deploy --config auth_wrangler.toml 2>&1
}

echo ""
echo "=== Done ==="
