#!/usr/bin/env bash
#
# Run on the PRODUCTION server. Unpacks a pre-built nextjs-standalone.tar.gz
# (built locally with scripts/build_nextjs_artifact.sh) and restarts the nextjs service.
# No npm run build on the server.
#
# Usage (from project root on server):
#   cd /var/www/boundary-fastapiandnextjs
#   # Put nextjs-standalone.tar.gz here (or pass path as first arg)
#   sudo bash scripts/unpack_and_start_nextjs.sh
#   # Or: sudo bash scripts/unpack_and_start_nextjs.sh /path/to/nextjs-standalone.tar.gz
#
set -e

APP_ROOT="${APP_ROOT:-/var/www/boundary-fastapiandnextjs}"
NEXT_DIR="$APP_ROOT/plagis-nextjs"

if [ -n "$1" ]; then
  TARBALL="$1"
else
  TARBALL="$APP_ROOT/nextjs-standalone.tar.gz"
fi

echo "=============================================="
echo "  Unpack Next.js artifact and start service"
echo "=============================================="
echo ""

if [ ! -f "$TARBALL" ]; then
  echo "Error: Tarball not found: $TARBALL"
  echo "Upload nextjs-standalone.tar.gz (from scripts/build_nextjs_artifact.sh) and run again."
  exit 1
fi

if [ ! -d "$NEXT_DIR" ]; then
  echo "Error: $NEXT_DIR not found."
  exit 1
fi

echo "[1/3] Extracting standalone into $NEXT_DIR..."
cd "$NEXT_DIR"
tar -xzvf "$TARBALL"
echo ""

echo "[2/3] Installing systemd unit (with correct node path) and restarting nextjs..."
bash "$APP_ROOT/scripts/install_nextjs_service.sh"
systemctl restart nextjs
echo ""

echo "[3/3] Checking status..."
sleep 2
if systemctl is-active --quiet nextjs; then
  echo "  nextjs: running"
  curl -sS -o /dev/null -w "  HTTP 127.0.0.1:3000 → %{http_code}\n" --connect-timeout 3 http://127.0.0.1:3000/ || true
else
  echo "  nextjs: failed to start. Run: journalctl -u nextjs -n 50 --no-pager"
  exit 1
fi
echo ""
echo "Done. Test the site in the browser."
