#!/usr/bin/env bash
# Deploy latest worker code into a cPanel folder that is NOT a git checkout.
# Run as root on the worker host:
#   curl -fsSL https://raw.githubusercontent.com/aicountly/apis-aicountly/main/worker.apis.aicountly.com/scripts/deploy-to-cpanel.sh | bash
# or copy this file to the server and: bash deploy-to-cpanel.sh

set -euo pipefail

TARGET="${QA_WORKER_ROOT:-/home/apisaicountly/public_html/worker.apis.aicountly.com}"
REPO_URL="${QA_WORKER_REPO:-https://github.com/aicountly/apis-aicountly.git}"
TMP="/tmp/apis-aicountly-worker-deploy-$$"

echo "==> Target: $TARGET"
if [ ! -d "$TARGET" ]; then
  echo "ERROR: target directory does not exist: $TARGET"
  exit 1
fi

if [ ! -f "$TARGET/.env" ]; then
  echo "ERROR: missing $TARGET/.env — aborting so secrets are not lost."
  exit 1
fi

echo "==> Backing up .env"
cp -a "$TARGET/.env" "/tmp/qa-worker.env.bak.$$"

echo "==> Cloning latest apis-aicountly"
rm -rf "$TMP"
git clone --depth 1 "$REPO_URL" "$TMP"

echo "==> Stopping qa-worker (if running)"
pm2 stop qa-worker >/dev/null 2>&1 || true

echo "==> Syncing worker source (keeps .env)"
rsync -a --delete \
  --exclude '.env' \
  --exclude 'node_modules' \
  --exclude '.git' \
  --exclude 'qa-reports' \
  "$TMP/worker.apis.aicountly.com/" \
  "$TARGET/"

cp -a "/tmp/qa-worker.env.bak.$$" "$TARGET/.env"
chown -R apisaicountly:apisaicountly "$TARGET" 2>/dev/null || true

echo "==> npm install"
cd "$TARGET"
npm install

echo "==> Verify live-progress code is present"
if ! grep -q 'postProgress' "$TARGET/apiClient.ts"; then
  echo "ERROR: apiClient.ts does not contain postProgress — deploy failed."
  exit 1
fi
if ! grep -q 'reportProgress' "$TARGET/runner/sessionRunner.ts"; then
  echo "ERROR: sessionRunner.ts does not contain reportProgress — deploy failed."
  exit 1
fi
echo "OK: live progress symbols found."

echo "==> Restart PM2"
cd "$TARGET"
if pm2 describe qa-worker >/dev/null 2>&1; then
  pm2 restart qa-worker --update-env
else
  pm2 start npm --name qa-worker --cwd "$TARGET" -- start
  pm2 save
fi

rm -rf "$TMP"
rm -f "/tmp/qa-worker.env.bak.$$"

echo "==> Status"
pm2 status qa-worker
echo
echo "Done. Start a NEW login QA run and open View log."
echo "You should see lines like: Preparing browser… / Opening login page… / LOGIN SUCCESSFUL"
echo
pm2 logs qa-worker --lines 40 --nostream
