#!/usr/bin/env bash
set -euo pipefail

APP_USER="aibit"
APP_NAME="testgiftmarketplace-web"
PORT="3023"
NODE_PATH="/opt/cpanel/ea-nodejs20/bin:/usr/local/bin:/usr/bin:/bin"
PM2_HOME="/home/aibit/.pm2"

# If deployment is invoked as root, immediately re-run it as aibit.
if [ "$(id -u)" -eq 0 ]; then
    exec runuser -u "$APP_USER" -- env \
        HOME="/home/aibit" \
        PM2_HOME="$PM2_HOME" \
        PATH="$NODE_PATH" \
        bash "$0" "$@"
fi

# Refuse to deploy as any account other than aibit.
if [ "$(id -un)" != "$APP_USER" ]; then
    echo "[deploy] ERROR: deployment must run as $APP_USER"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
FRONTEND="$(cd "$SCRIPT_DIR/../../frontend/current" && pwd)"

export HOME="/home/aibit"
export PM2_HOME="$PM2_HOME"
export PATH="$NODE_PATH"
export NODE_ENV="production"

cd "$FRONTEND"

echo "[deploy] Installing locked dependencies..."
npm ci --legacy-peer-deps

echo "[deploy] Building $APP_NAME..."
npm run build

echo "[deploy] Removing previous aibit PM2 instance..."
pm2 delete "$APP_NAME" >/dev/null 2>&1 || true

# Never kill an arbitrary process that owns the production port.
if ss -ltn | grep -q ":${PORT} "; then
    echo "[deploy] ERROR: port ${PORT} is still occupied."
    echo "[deploy] Refusing to kill the existing port owner."
    exit 1
fi

echo "[deploy] Starting $APP_NAME on port $PORT..."
pm2 start npm \
    --name "$APP_NAME" \
    --cwd "$FRONTEND" \
    --max-memory-restart 512M \
    -- start -- -p "$PORT"

sleep 2

curl -fsS --max-time 10 "http://127.0.0.1:${PORT}/" >/dev/null

pm2 save

echo "[deploy] Success: https://testgiftmarketplace.aibit.services/"
