#!/usr/bin/env bash
# SEO Insight — one-shot PRODUCTION update, triggered FROM your local machine.
#
# SSHes into the VPS and runs deploy/deploy.sh as the `seoinsight` user. The
# deploy itself forces the `main` branch (main = PRODUCTION), so there's nothing
# to choose here: run it after `dev` has been fast-forwarded into `main` and
# pushed.
#
#   ./seo-insight-update.sh
#
# Configure the SSH target once (either edit SEO_INSIGHT_HOST below, or export it
# in your shell profile):
#   export SEO_INSIGHT_HOST="sgwsnlcupaqyxdqux@163.172.71.169"
#
# Overridable knobs:
#   SEO_INSIGHT_HOST    SSH target — a sudo-capable user@host (NOT seoinsight).   [required]
#   SEO_INSIGHT_DIR     App dir on the VPS.                                        [/opt/seo-insight]
#   DEPLOY_BRANCH       Branch the VPS deploy tracks.                              [main]
set -euo pipefail

# ── Fill this in (or export SEO_INSIGHT_HOST in your shell) ───────────────────
HOST="${SEO_INSIGHT_HOST:-CHANGEME_user@your-vps-host}"
APP_DIR="${SEO_INSIGHT_DIR:-/opt/seo-insight}"
BRANCH="${DEPLOY_BRANCH:-main}"

if [ "$HOST" = "CHANGEME_user@your-vps-host" ]; then
  echo "✗ Set the SSH target first:" >&2
  echo "    export SEO_INSIGHT_HOST=\"sgwsnlcupaqyxdqux@163.172.71.169\"" >&2
  echo "  …or edit HOST at the top of $(basename "$0")." >&2
  exit 1
fi

echo "▸ Updating PRODUCTION on $HOST (branch '$BRANCH', dir $APP_DIR)…"

# -t: allocate a TTY so the remote `sudo` can prompt for a password if needed.
# We run the deploy as `seoinsight` (the app's system user) via sudo. The deploy
# script reads DEPLOY_BRANCH, so we forward it; sudo's `--preserve-env` keeps it
# across the privilege drop.
ssh -t "$HOST" \
  "sudo --preserve-env=DEPLOY_BRANCH -u seoinsight env DEPLOY_BRANCH='$BRANCH' \
     bash -lc 'cd $APP_DIR && ./deploy/deploy.sh'"

echo "✓ Update triggered. Tail the live logs with:"
echo "    ssh $HOST \"sudo journalctl -u seo-insight-web -u seo-insight-analytics -f\""
