#!/usr/bin/env bash
# サンドニエット SANDONIETTE — deploy to partly.party/sandoniette/
# Games VPS: humanjing@100.71.119.27 (tailscale), docker container forum-nginx,
# nginx serves /usr/share/nginx/html/<game>/ at partly.party/<game>/.
#
# Usage: bash deploy.sh   (builds fresh, then ships dist/)
set -euo pipefail

VPS="humanjing@100.71.119.27"
CONTAINER="forum-nginx"
WEB_ROOT="/usr/share/nginx/html/sandoniette"
STAGING="/tmp/sandoniette_deploy"
DIR="$(cd "$(dirname "$0")" && pwd)"

echo "[1/5] Building (base=/sandoniette/) ..."
( cd "$DIR" && npm run build >/dev/null )
echo "      ✓ dist/ ready"

echo "[2/5] Rsync dist/ → VPS staging ..."
ssh "$VPS" "rm -rf '$STAGING' && mkdir -p '$STAGING'"
rsync -az --delete "$DIR/dist/" "$VPS:$STAGING/"
echo "      ✓ synced"

echo "[3/5] Reset container web root ..."
ssh "$VPS" "docker exec $CONTAINER sh -c 'rm -rf ${WEB_ROOT:?} && mkdir -p ${WEB_ROOT:?}'"

echo "[4/5] Copy bundle into container ..."
ssh "$VPS" "docker cp $STAGING/. $CONTAINER:$WEB_ROOT/"
ssh "$VPS" "rm -rf '$STAGING'"
echo "      ✓ live files in place"

echo "[5/5] Verify ..."
code=$(curl -s -o /dev/null -w '%{http_code}' https://partly.party/sandoniette/ || true)
js=$(curl -s https://partly.party/sandoniette/ | grep -o '/sandoniette/assets/[^"]*\.js' | head -1)
jscode=$(curl -s -o /dev/null -w '%{http_code}' "https://partly.party$js" || true)
echo "      index: $code   $js: $jscode"

echo ""
echo "✓ Live at https://partly.party/sandoniette/  (Cloudflare-fronted; purge cache after big changes)"
