#!/usr/bin/env bash
# =============================================================================
# RecreaHUB API — Linux Server Setup (Ubuntu / Debian)
# Run as root or with sudo: sudo bash setup-linux.sh
# =============================================================================
set -euo pipefail

DEPLOY_DIR="/opt/recreahub-api"
APP_PORT=3000

echo ""
echo "============================================================"
echo "  RecreaHUB API — Linux Setup"
echo "============================================================"
echo ""

# ── 1. Install Node.js 20 LTS via NodeSource ─────────────────────────────────
echo "[1/7] Installing Node.js 20 LTS..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
node -v
npm -v

# ── 2. Install PM2 globally ───────────────────────────────────────────────────
echo "[2/7] Installing PM2 globally..."
npm install -g pm2

# ── 3. Navigate to deploy directory ──────────────────────────────────────────
echo "[3/7] Navigating to ${DEPLOY_DIR}..."
if [ ! -d "${DEPLOY_DIR}" ]; then
  echo "  ERROR: Deploy directory ${DEPLOY_DIR} not found."
  echo "  Please deploy the application files first, then re-run this script."
  exit 1
fi
cd "${DEPLOY_DIR}"

# ── 4. Install production dependencies ───────────────────────────────────────
echo "[4/7] Installing production dependencies..."
npm install --omit=dev

# ── 5. Start the application with PM2 ────────────────────────────────────────
echo "[5/7] Starting RecreaHUB API with PM2 (production mode)..."
pm2 start ecosystem.config.js --env production

# ── 6. Save PM2 process list ──────────────────────────────────────────────────
echo "[6/7] Saving PM2 process list..."
pm2 save

# ── 7. Configure PM2 to start on boot ────────────────────────────────────────
echo "[7/7] Generating PM2 startup script..."
echo ""
echo "------------------------------------------------------------"
echo "  IMPORTANT: Copy and run the command shown below to enable"
echo "  PM2 auto-start on system reboot:"
echo "------------------------------------------------------------"
pm2 startup
echo "------------------------------------------------------------"
echo "  After running that command, execute: pm2 save"
echo "------------------------------------------------------------"

echo ""
echo "============================================================"
echo "  Setup complete!"
echo "  RecreaHUB API is running at http://$(hostname -I | awk '{print $1}'):${APP_PORT}"
echo "  Health check: http://$(hostname -I | awk '{print $1}'):${APP_PORT}/health"
echo ""
echo "  Useful PM2 commands:"
echo "    pm2 status              — view running processes"
echo "    pm2 logs recreahub-api  — stream logs"
echo "    pm2 reload recreahub-api --update-env  — zero-downtime reload"
echo "============================================================"
