#!/usr/bin/env bash
#
# deploy.sh — Install deps and restart the app on cPanel (Phusion Passenger).
#
# Run this ON THE SERVER from the application root, e.g.:
#   cd ~/Municipal-Backend && bash deploy.sh           # restart only
#   cd ~/Municipal-Backend && bash deploy.sh --pull    # git pull first, then restart
#
# What it does:
#   1. (optional, with --pull) git pull --ff-only
#   2. Activates the cPanel Node.js virtualenv
#   3. Runs `npm ci` only when package-lock.json changed
#   4. Restarts the app via Passenger's tmp/restart.txt (no cPanel UI needed)
#
set -euo pipefail

# --- Parse args --------------------------------------------------------------
DO_PULL=false
for arg in "$@"; do
  case "$arg" in
    --pull|pull) DO_PULL=true ;;
    *) echo "Unknown argument: $arg (supported: --pull)"; exit 1 ;;
  esac
done

# --- Resolve paths -----------------------------------------------------------
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_NAME="$(basename "$APP_DIR")"
cd "$APP_DIR"

echo "==> Deploying $APP_NAME ($APP_DIR)"

# --- Capture lockfile hash before pulling ------------------------------------
LOCK_BEFORE=""
[ -f package-lock.json ] && LOCK_BEFORE="$(md5sum package-lock.json | awk '{print $1}')"

# --- Pull latest code (opt-in) -----------------------------------------------
if [ "$DO_PULL" = true ]; then
  echo "==> git pull"
  git pull --ff-only
else
  echo "==> Skipping git pull (pass --pull to enable)"
fi

# --- Activate the cPanel Node.js virtualenv ----------------------------------
# cPanel creates it at ~/nodevenv/<app>/<version>/. Pick the highest version found.
VENV_BASE="$HOME/nodevenv/$APP_NAME"
if [ -d "$VENV_BASE" ]; then
  VENV_VER="$(ls -1 "$VENV_BASE" | sort -V | tail -n 1)"
  ACTIVATE="$VENV_BASE/$VENV_VER/bin/activate"
  if [ -f "$ACTIVATE" ]; then
    echo "==> Activating Node.js venv: $VENV_VER"
    # cPanel's activate script references unbound vars (e.g. CL_VIRTUAL_ENV),
    # so relax `set -u` just while sourcing it.
    set +u
    # shellcheck disable=SC1090
    source "$ACTIVATE"
    set -u
  fi
else
  echo "!! No nodevenv found at $VENV_BASE — using system node ($(command -v node))"
fi

# --- Install dependencies only if the lockfile changed -----------------------
LOCK_AFTER=""
[ -f package-lock.json ] && LOCK_AFTER="$(md5sum package-lock.json | awk '{print $1}')"
if [ "$LOCK_BEFORE" != "$LOCK_AFTER" ]; then
  echo "==> package-lock.json changed — running npm ci"
  npm ci --omit=dev
else
  echo "==> Dependencies unchanged — skipping npm ci"
fi

# --- Restart the app (Passenger) ---------------------------------------------
echo "==> Restarting app via Passenger"
mkdir -p tmp
touch tmp/restart.txt

echo "==> Done. App will reload on the next request."
echo "    Tail logs with: tail -f $APP_DIR/logs/app.log"
