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

# -------------------------------------------------------------------
# Mozart deploy — pull latest code, rebuild, and restart.
# Run as the mozart user (or any user with sudo).
# -------------------------------------------------------------------

REPO_DIR="${HOME}/mozart"
cd "$REPO_DIR"

echo "=== Pulling latest code ==="
git pull --ff-only

echo "=== Installing dependencies ==="
bun install
(cd ui && bun install)

echo "=== Building ==="
bun run build

echo "=== Rebuilding Podman agent images ==="
./mozart setup --rebuild

echo "=== Restarting Mozart daemon ==="
sudo systemctl restart mozart

echo ""
echo "Deploy complete. Checking health..."
sleep 3

for i in $(seq 1 10); do
  if curl -sf localhost:4141/health | grep -q '"ready":true'; then
    echo "Mozart is healthy."
    exit 0
  fi
  sleep 1
done

echo "Warning: health check not yet passing. Check: sudo systemctl status mozart"
exit 1
