#!/usr/bin/env bash
# =====================================================================
# BLOBBO — Deploy to partly.party/blobbo/
# =====================================================================
# Usage: bash deploy.sh   (from the BLOBBO repo root)
#
#   1. npm run build (vite, base=/blobbo/)
#   2. rsync dist/ to VPS staging
#   3. docker cp into forum-nginx web root
#   4. curl verify (cache-busted)
#
# Follows the GAMES/ deploy doctrine (see cratewars/deploy.sh template).
# Requirements: ssh humanjing@100.71.119.27 (tailscale), container forum-nginx.
# =====================================================================
set -euo pipefail

VPS="humanjing@100.71.119.27"
CONTAINER="forum-nginx"
REMOTE_WEB_ROOT="/usr/share/nginx/html/blobbo"
STAGING="/tmp/blobbo_deploy"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "[1/4] Building ..."
cd "$SCRIPT_DIR"
npm run build

echo "[2/4] Syncing dist/ to VPS staging ..."
ssh "$VPS" "rm -rf '$STAGING' && mkdir -p '$STAGING'"
rsync -az --exclude='.DS_Store' "$SCRIPT_DIR/dist/" "$VPS:$STAGING/"

echo "[3/4] Replacing container content ..."
ssh "$VPS" "docker exec $CONTAINER sh -c 'rm -rf ${REMOTE_WEB_ROOT:?}' && docker cp $STAGING/. $CONTAINER:$REMOTE_WEB_ROOT/"

echo "[4/4] Verifying live URL ..."
BUST="$(date +%s)"
CODE_HTTP="$(ssh "$VPS" "curl -s -o /dev/null -w '%{http_code}' http://localhost/blobbo/?v=$BUST")"
echo "      container-local /blobbo/ -> HTTP $CODE_HTTP"
CODE_LIVE="$(curl -s -o /dev/null -w '%{http_code}' "https://partly.party/blobbo/?v=$BUST")"
echo "      https://partly.party/blobbo/ -> HTTP $CODE_LIVE"
[ "$CODE_LIVE" = "200" ] || { echo "      ✗ live check failed"; exit 1; }
echo "      ✓ deployed."
