#!/usr/bin/env bash
# One-shot deploy for the Trading Bite community app on a VPS (run over SSH).
# Usage:  cd into the app folder (where server.js is), then:  bash deploy.sh
# Safe to re-run any time (it just reinstalls deps and restarts the app).

set -e
APP_NAME="trading-bite"
PORT="${PORT:-3100}"

echo "==> Deploying $APP_NAME on port $PORT"

# 1. Node.js (install if missing)
if ! command -v node >/dev/null 2>&1; then
  echo "==> Node.js not found — installing Node 20"
  if command -v dnf >/dev/null 2>&1; then
    curl -fsSL https://rpm.nodesource.com/setup_20.x | bash - && dnf install -y nodejs
  elif command -v yum >/dev/null 2>&1; then
    curl -fsSL https://rpm.nodesource.com/setup_20.x | bash - && yum install -y nodejs
  elif command -v apt-get >/dev/null 2>&1; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs
  else
    echo "!! Could not detect a package manager. Install Node 18+ manually, then re-run." ; exit 1
  fi
fi
echo "==> Using $(node -v)"

# 2. Dependencies
echo "==> Installing dependencies"
npm install --production --no-audit --no-fund

# 3. Writable data dirs
mkdir -p data uploads
chmod 755 data uploads

# 4. Process manager (PM2 keeps it running + restarts on reboot/crash)
if ! command -v pm2 >/dev/null 2>&1; then
  echo "==> Installing PM2"
  npm install -g pm2
fi

echo "==> Starting/restarting the app"
pm2 delete "$APP_NAME" >/dev/null 2>&1 || true
PORT="$PORT" pm2 start server.js --name "$APP_NAME"
pm2 save
pm2 startup 2>/dev/null | tail -n 1 || true   # prints the command to enable boot-start (run it once as root)

echo ""
echo "==> DONE. App is running on http://127.0.0.1:$PORT"
echo "    Next: point your domain to this port (cPanel Application Manager or an Apache/nginx"
echo "    reverse proxy), run AutoSSL for HTTPS, then change the admin password + set data/email.json."
echo "    Check status:  pm2 status        Logs:  pm2 logs $APP_NAME"
