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

APP_DIR=${APP_DIR:-$(pwd)}
PM2_NAME=${PM2_NAME:-whatsapp-inbox-platform}
PORT=${PORT:-3002}
SKIP_DB=${SKIP_DB:-0}
SKIP_HEALTHCHECK=${SKIP_HEALTHCHECK:-0}

if [ ! -f "$APP_DIR/.env" ]; then
  echo "[ops-safe-restart] .env file not found in $APP_DIR"
  exit 1
fi

cd "$APP_DIR"

echo "[ops-safe-restart] install dependencies"
npm ci --no-audit --no-fund

echo "[ops-safe-restart] run build"
npm run build

if [ "$SKIP_DB" != "1" ]; then
  echo "[ops-safe-restart] apply prisma migration"
  npm run db:deploy
fi

if pm2 describe "$PM2_NAME" >/dev/null 2>&1; then
  echo "[ops-safe-restart] restart existing pm2 process: $PM2_NAME"
  pm2 restart "$PM2_NAME" --update-env
else
  echo "[ops-safe-restart] start new pm2 process: $PM2_NAME"
  pm2 start npm --name "$PM2_NAME" -- start -- --port "$PORT"
fi

if [ "$SKIP_HEALTHCHECK" != "1" ]; then
  echo "[ops-safe-restart] run ops healthcheck"
  npm run ops:healthcheck
fi

echo "[ops-safe-restart] saving pm2 process list"
pm2 save

echo "[ops-safe-restart] done"
