#!/bin/bash
# Production deploy for the chatbot widget, run on the server
# (licenseeportal account) from the repo checkout at
# ~/ai-chat-youngengineers-repo.
#
# Mirrors Licensee-Portal's bin/deploy.sh pattern exactly (same cPanel
# account, same overall pipeline) - the one real difference is that this
# repo IS the app (no monorepo subtree to pick out), so the rsync source is
# the repo root itself.
#
# Idempotent: safe to run on the very first bootstrap (right after the repo
# is cloned) or on every deploy after - pulls latest main, rsyncs the app
# into the docroot (preserving .env/.env.local/node_modules/.next), builds
# with automatic rollback on a failed build, and starts/reloads PM2.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$REPO_ROOT"

SERVE="$HOME/public_html/aichat.youngengineers.org"

# Repo is private - plain HTTPS has no credentials on this account. Use the
# dedicated read-only deploy key instead (generated once directly on the
# server at ~/.ssh/aichat_repo_deploy, registered as a read-only GitHub
# deploy key on this repo - never given write access).
export GIT_SSH_COMMAND="ssh -i ~/.ssh/aichat_repo_deploy -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"

echo "--- Pulling latest main ---"
git fetch origin main -q
git reset --hard origin/main -q

echo "--- Syncing app into docroot ---"
mkdir -p "$SERVE"
rsync -a --delete \
  --exclude='.git' \
  --exclude='.env' \
  --exclude='.env.local' \
  --exclude='node_modules' \
  --exclude='.next' \
  ./ "$SERVE/"

cd "$SERVE"

echo "--- Installing dependencies ---"
npm install --prefer-offline --no-audit --no-fund

# Back up the last good build so we can restore on failure - the old
# version keeps serving under PM2 while this build runs.
if [ -d "$SERVE/.next" ]; then
  echo "--- Backing up current .next build ---"
  rm -rf "$SERVE/.next.bak"
  cp -r "$SERVE/.next" "$SERVE/.next.bak"
fi

echo "--- Building ---"
if ! NODE_ENV=production npm run build; then
  echo "::error::Next.js build failed." >&2
  if [ -d "$SERVE/.next.bak" ]; then
    echo "--- Restoring previous .next build to keep site online ---"
    rm -rf "$SERVE/.next"
    mv "$SERVE/.next.bak" "$SERVE/.next"
  fi
  exit 1
fi
rm -rf "$SERVE/.next.bak"

echo "--- Starting/reloading PM2 ---"
if pm2 describe aichat-app > /dev/null 2>&1; then
  pm2 restart aichat-app --update-env
else
  pm2 start npm --name aichat-app --cwd "$SERVE" -- start
fi
pm2 save --force

echo "--- Deploy complete ---"
