#!/usr/bin/env bash
#
# Deploys the Next.js frontend from a git checkout already present on the
# production host - see docs/DEPLOYMENT.md. Pulls the given branch, installs
# dependencies, builds a production bundle, then restarts the long-running
# `next start` process via PM2 if it's installed - PM2 is the simplest
# cross-platform way to keep a Node process alive and auto-restarting on
# this stack (no Docker, no systemd assumed). Prints manual restart
# instructions instead if PM2 isn't set up yet. Bash equivalent of
# deploy-web.ps1 for hosts without PowerShell Core installed.
#
# Usage:
#   ./scripts/deploy-web.sh
#   ./scripts/deploy-web.sh --branch dev-initial --process-name domainops-web

set -euo pipefail

BRANCH="main"
PROCESS_NAME="domainops-web"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --branch)
      BRANCH="$2"
      shift 2
      ;;
    --process-name)
      PROCESS_NAME="$2"
      shift 2
      ;;
    *)
      echo "Unknown option: $1" >&2
      exit 1
      ;;
  esac
done

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

if [[ ! -f .env.production && ! -f .env ]]; then
  echo "No .env.production (or .env) found at $ROOT - copy .env.production.example (or .env.staging.example) to .env.production and fill it in before deploying." >&2
  exit 1
fi

echo "Fetching '$BRANCH' ..."
git fetch origin "$BRANCH"
git checkout "$BRANCH"
git pull origin "$BRANCH"

echo "Installing dependencies ..."
npm ci

echo "Building production bundle ..."
npm run build

if command -v pm2 >/dev/null 2>&1; then
  echo "Restarting PM2 process '$PROCESS_NAME' ..."
  if pm2 describe "$PROCESS_NAME" >/dev/null 2>&1; then
    pm2 restart "$PROCESS_NAME"
  else
    pm2 start npm --name "$PROCESS_NAME" -- run start
  fi
  pm2 save
else
  echo "Warning: PM2 isn't installed - install it once with 'npm install -g pm2', then run:" >&2
  echo "  pm2 start npm --name $PROCESS_NAME -- run start" >&2
  echo "Until then, restart the 'npm run start' process for this app manually." >&2
fi

echo "Web deploy complete."
