#!/bin/bash
# Simple deploy script: pull main on VPS, install, build API/Web, sync front, restart API + Caddy.
set -euo pipefail

VPS_HOST="ubuntu@51.38.241.179"
APP_USER="myroadtrip"
APP_DIR="/srv/myroadtrip"
REPO_DIR="$APP_DIR/repo"
WEB_ROOT="/srv/www/roadtripper"

echo "🚀 Deploying to $VPS_HOST ..."

ssh "$VPS_HOST" bash -lc "'
set -euo pipefail

echo \"[1/5] Fix permissions\"
sudo chown -R $APP_USER:$APP_USER $APP_DIR $WEB_ROOT
sudo chmod -R u+rwX $APP_DIR

echo \"[2/5] Update repo\"
cd $REPO_DIR
git fetch origin
git checkout main
git pull --ff-only origin main

echo \"[3/5] Install + build\"
pnpm install
pnpm --filter @my-roadtrip/api run build
pnpm --filter @my-roadtrip/web run build

echo \"[4/5] Sync frontend\"
rsync -a --delete $REPO_DIR/apps/web/dist/ $WEB_ROOT/

echo \"[5/5] Restart services\"
sudo systemctl restart myroadtrip-api
sudo systemctl reload caddy

echo \"✅ Deploy complete on VPS\"
'"

echo "Done."
