#!/usr/bin/env bash
# One command on the mail server (as user ronnie) after git pull.
# Fixes "tsc: command not found" and restarts API + email workers + inbound pipe.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

echo ">> Deploy from: ${ROOT}"
echo ">> User: $(whoami) | Node: $(node -v 2>/dev/null || echo 'missing')"

if ! command -v node >/dev/null 2>&1; then
  echo "ERROR: node not found. Load nvm or install Node 20+."
  exit 1
fi

echo ">> Git: fetch + reset to origin/main"
git fetch origin main --prune
git reset --hard origin/main

chmod +x scripts/post-deploy.sh scripts/setup-inbound-pipe.sh 2>/dev/null || true

echo ">> Full deploy (npm ci, build, migrate, pm2, inbound pipe)"
bash scripts/post-deploy.sh

echo ""
echo ">> Done. Check:"
echo "   pm2 list"
echo "   curl -s http://127.0.0.1:\$(grep -E '^PORT=' .env | cut -d= -f2 | tr -d ' ')/health"
echo "   tail -f ~/logs/email-inbound-pipe.log"
