#!/usr/bin/env bash
# Build locally is not assumed — this builds on the server, so the
# deployed artifact matches the server's Node and architecture.
#
#   ssh onairada@host 'bash -s' < deploy/deploy.sh
# or, on the server:  bash deploy/deploy.sh
set -euo pipefail

# Default to the directory this script lives in, not a guessed path.
#
# It previously defaulted to $HOME/app while the app is deployed at
# $HOME/public_html, so running it from the app root deployed the wrong
# copy — or nothing — while still printing "Done". Deriving the path from
# the script's own location cannot drift from where the code actually is.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR="${APP_DIR:-$(cd "$SCRIPT_DIR/.." && pwd)}"

cd "$APP_DIR"

echo "==> Pulling"
git pull --ff-only

echo "==> Installing (including dev deps: the build needs TypeScript)"
npm ci

echo "==> Building shared, api, web"
npm run build

# Next's standalone output deliberately omits static assets and public/.
# Without this copy the site renders unstyled with no client JS, and every
# file under public/ 404s — which is how the source icons shipped as broken
# images after a hand-run deploy skipped this step.
#
# The targets are removed first: `cp -r src dest` where dest exists nests
# the folder inside it (dest/static/static) instead of replacing it, so a
# redeploy over a previous one silently keeps serving the old files.
echo "==> Copying static assets into the standalone bundle"
STANDALONE="apps/web/.next/standalone/apps/web"
rm -rf "$STANDALONE/.next/static"
cp -r apps/web/.next/static "$STANDALONE/.next/static"
if [ -d apps/web/public ]; then
  rm -rf "$STANDALONE/public"
  cp -r apps/web/public "$STANDALONE/public"
fi

# Verify rather than assume: this step has failed silently before, and the
# result is a site that looks deployed but serves broken assets.
for check in "$STANDALONE/.next/static" "$STANDALONE/public/sources"; do
  if [ ! -d "$check" ]; then
    echo "ERROR: $check is missing after the copy — the site would serve broken assets." >&2
    exit 1
  fi
done

echo "==> Running database migrations"
npm run db:migrate

mkdir -p "$HOME/logs"

echo "==> Restarting processes"
if pm2 describe ai-radar-api >/dev/null 2>&1; then
  # reload keeps the old process serving until the new one is listening.
  pm2 reload ecosystem.config.js
else
  pm2 start ecosystem.config.js
  pm2 save
fi

pm2 status
echo "==> Done"
