#!/usr/bin/env bash
# Refresh the waterland checkout and rebuild the studio image.
#
# The checkout deliberately lives OUTSIDE the compose directory:
# deploy-stack.sh rsyncs stacks/<stack>/ with --delete, so a checkout kept
# beside compose.yaml would be deleted by the next deploy of this stack.
#
# Run ON irv-ml1:
#   /opt/docker/compose/waterland-studio/update.sh
set -euo pipefail

SRC=/opt/waterland-studio/src
COMPOSE_DIR=/opt/docker/compose/waterland-studio
REPO_URL=${WATERLAND_REPO_URL:-https://gitea.phasefinal.com/vh/waterland.git}
REF=${WATERLAND_REF:-main}

if [ ! -d "$SRC/.git" ]; then
  echo "no checkout at $SRC — clone it first:"
  echo "  sudo mkdir -p $(dirname "$SRC")"
  echo "  sudo git clone $REPO_URL $SRC"
  exit 1
fi

echo "==> fetching $REF"
git -C "$SRC" fetch --prune origin
git -C "$SRC" checkout -q "$REF"
git -C "$SRC" reset --hard "origin/$REF"
echo "==> now at $(git -C "$SRC" rev-parse --short HEAD): $(git -C "$SRC" log -1 --format=%s)"

echo "==> rebuilding"
cd "$COMPOSE_DIR"
docker compose build --pull

echo "==> restarting"
docker compose up -d

echo "==> waiting for health"
for _ in $(seq 1 30); do
  if curl -fsS -m 5 http://127.0.0.1:8410/api/health >/dev/null 2>&1; then
    echo "healthy: $(curl -fsS -m 5 http://127.0.0.1:8410/api/health)"
    exit 0
  fi
  sleep 3
done
echo "did not come healthy within 90s — check: docker compose logs --tail 50" >&2
exit 1
