#!/usr/bin/env bash
set -euo pipefail

# Simple pull-based deployer for the VPS, bypassing GitHub Actions.
# - Syncs repo with origin/main
# - Reapplies Swarm stack
# - If convex/ changed, deploys Convex functions to self-hosted backend
#
# Requirements:
# - Run from /srv/apps/sistema (or set APP_DIR below)
# - A file .ci.env with:
#     CONVEX_SELF_HOSTED_URL=https://convex.esdrasrenan.com.br
#     CONVEX_SELF_HOSTED_ADMIN_KEY=convex-self-hosted|...

APP_DIR=${APP_DIR:-/srv/apps/sistema}
cd "$APP_DIR"

echo "[deploy] Fetching origin/main..."
git fetch origin main --quiet

CURRENT=$(git rev-parse HEAD || echo "")
REMOTE=$(git rev-parse origin/main)

if [[ "$CURRENT" == "$REMOTE" ]]; then
  echo "[deploy] Nothing to do (up-to-date)."
  exit 0
fi

echo "[deploy] Computing changed paths..."
CHANGED=$(git diff --name-only "${CURRENT:-$REMOTE}" "$REMOTE" || true)

echo "[deploy] Resetting to origin/main ($REMOTE)..."
git reset --hard "$REMOTE"

echo "[deploy] Re-deploying Swarm stack..."
docker stack deploy --with-registry-auth -c stack.yml sistema

if echo "$CHANGED" | grep -q '^convex/'; then
  if [[ -f .ci.env ]]; then
    echo "[deploy] convex/ changed -> deploying Convex functions..."
    docker run --rm -i \
      -v "$APP_DIR":/app \
      -w /app \
      --env-file .ci.env \
      oven/bun:1 bash -lc "bun install --frozen-lockfile && bun x convex deploy"
  else
    echo "[deploy] convex/ changed but .ci.env missing; skip Convex deploy"
  fi
else
  echo "[deploy] convex/ unchanged; skipping Convex deploy"
fi

echo "[deploy] Done."
