#!/bin/bash
# Production deploy for the franchisee frontend, run on the server
# (licenseeweb account) inside one of the two app checkouts:
#   ~/public_html/franchisees-website          (PORT 3003, PM2 app franchisee-global-app)
#   ~/public_html/preview.youngengineers.org   (PORT 3002, PM2 app franchisee-preview-app)
#
# Both directories are independent clones of the same repo/branch - this
# script deploys whichever one it's run from, given that checkout's port
# and PM2 app name as arguments. Idempotent: safe on first bootstrap
# (right after the repo is force-reset in place) or on every deploy after.
set -euo pipefail
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

PM2_PORT="${1:?Usage: bin/deploy.sh <port> <pm2-app-name>}"
PM2_NAME="${2:?Usage: bin/deploy.sh <port> <pm2-app-name>}"

# Repo is private - use the dedicated read-only deploy key generated once
# directly on the server (~/.ssh/franchisees_repo_deploy), registered as a
# read-only GitHub deploy key on this repo - never given write access.
export GIT_SSH_COMMAND="ssh -i ~/.ssh/franchisees_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 .htaccess (blocks direct access to .env etc.) ---"
cp -f deploy/htaccess .htaccess

echo "--- Checking if dependencies changed ---"
if ! cmp -s package-lock.json node_modules/.package-lock.json-copy 2>/dev/null; then
  echo "Changes detected - installing dependencies"
  npm ci
  cp package-lock.json node_modules/.package-lock.json-copy
else
  echo "No dependency changes - skipping npm install"
fi

echo "--- Backing up previous build ---"
rm -rf .next_backup
cp -r .next .next_backup 2>/dev/null || true

echo "--- Building ---"
if npm run build; then
  echo "Build succeeded"
  rm -rf .next_backup
else
  echo "Build failed - restoring previous build"
  rm -rf .next
  mv .next_backup .next
  echo "Old build restored - PM2 left untouched"
  exit 1
fi

echo "--- Starting/reloading PM2 ($PM2_NAME on port $PM2_PORT) ---"
PORT="$PM2_PORT" pm2 restart "$PM2_NAME" || PORT="$PM2_PORT" pm2 start npm --name "$PM2_NAME" -- start
pm2 save

echo "--- Deploy complete ($PM2_NAME) ---"
