#!/usr/bin/env bash
# Deploy TokNext to VPS.
#
# Usage:
#   ./scripts/deploy.sh            # build + deploy
#   ./scripts/deploy.sh --skip-build  # deploy without rebuilding
#
# Requires: rsync, ssh
# With password auth: install sshpass first
#   macOS:  brew install hudochenkov/sshpass/sshpass
#   Linux:  apt install sshpass / yum install sshpass
#
# Setup:
#   cp .deploy.env.example .deploy.env
#   # fill in SSH_PASS (or leave blank and use SSH keys)
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$SCRIPT_DIR/.deploy.env"

# Load deploy config
if [[ -f "$ENV_FILE" ]]; then
  source "$ENV_FILE"
fi

VPS_HOST="${VPS_HOST:-root@72.60.118.86}"
VPS_APP_DIR="${VPS_APP_DIR:-/home/toknext/public_html/app/toknext-next}"
SSH_PASS="${SSH_PASS:-}"
SKIP_BUILD=false

for arg in "$@"; do
  [[ "$arg" == "--skip-build" ]] && SKIP_BUILD=true
done

# Build SSH/rsync wrappers
if [[ -n "$SSH_PASS" ]]; then
  if ! command -v sshpass &>/dev/null; then
    echo "ERROR: SSH_PASS is set but sshpass is not installed."
    echo "  macOS: brew install hudochenkov/sshpass/sshpass"
    echo "  Linux: apt install sshpass"
    exit 1
  fi
  _SSH="sshpass -p $SSH_PASS ssh -o StrictHostKeyChecking=no"
  _RSYNC="sshpass -p $SSH_PASS rsync"
else
  _SSH="ssh"
  _RSYNC="rsync"
fi

echo "==> Target: $VPS_HOST:$VPS_APP_DIR"

# 1. Build
if [[ "$SKIP_BUILD" == false ]]; then
  echo "==> Building..."
  cd "$SCRIPT_DIR"
  npm run build
fi

# 2. Sync files (exclude secrets and dev artifacts)
echo "==> Syncing files..."
$_RSYNC -az --delete \
  --exclude='.git' \
  --exclude='.env' \
  --exclude='.env.*' \
  --exclude='.deploy.env' \
  --exclude='node_modules' \
  --exclude='.next/cache' \
  "$SCRIPT_DIR/" \
  "$VPS_HOST:$VPS_APP_DIR/"

# 3. Remote: install deps, migrate, restart
echo "==> Installing + migrating + restarting..."
$_SSH "$VPS_HOST" bash <<'REMOTE'
set -e
APP_DIR="/home/toknext/public_html/app/toknext-next"
export PATH=/opt/node20/bin:$PATH

cd "$APP_DIR"
# Next/Tailwind v4 and Prisma generate require packages that are currently
# declared as devDependencies. Install the full lockfile before generate,
# migrate, and PM2 restart.
npm ci
npx prisma generate
npx prisma migrate deploy
pm2 restart toknext --update-env
pm2 save
echo "Done."
REMOTE

echo ""
echo "==> Deploy complete. Check: https://toknext.com"
