#!/usr/bin/env bash
# Deploy ONLY testgiftmarketplace.aibit.services (PM2 name + port 3023).
# Does NOT touch giftmarketplace-web (prod on 3022) or other PM2 apps.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
FRONTEND="$(cd "$SCRIPT_DIR/../../frontend/current" && pwd)"
BASE="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
LOG_DIR="${BASE}/log/GIFTMarketplace/pm2"

mkdir -p "$LOG_DIR"
cd "$FRONTEND"

export NODE_ENV=production
export PATH="/root/.nvm/versions/node/v20.19.5/bin:$PATH"

echo "[deploy] Building testgiftmarketplace-web from ${FRONTEND}..."
yarn run build

echo "[deploy] Restarting PM2 app testgiftmarketplace-web on port 3023..."
pm2 delete testgiftmarketplace-web >/dev/null 2>&1 || true
pm2 start /home/aibitsofts/scripts/pm2-free-port.sh \
  --name testgiftmarketplace-web \
  --cwd "$FRONTEND" \
  --output "$LOG_DIR/out.log" \
  --error "$LOG_DIR/error.log" \
  --interpreter bash \
  -- 3023 node node_modules/next/dist/bin/next start -p 3023

pm2 save
echo "[deploy] Done. Live at https://testgiftmarketplace.aibit.services/"
