#!/usr/bin/env bash
# Block until the deployed site is serving the commit at local HEAD.
#
#   git push && bin/wait-deploy
#
# Works from any machine — it only reads the public /api/version endpoint, so
# no Coolify token and no SSH tunnel are needed.
set -uo pipefail

URL=${URL:-https://chart.amow.com}
TIMEOUT=${TIMEOUT:-300}

want=$(git rev-parse HEAD) || exit 1
short=${want:0:8}

echo "waiting for $URL to serve $short (timeout ${TIMEOUT}s)"

start=$(date +%s)
last=""
while :; do
  now=$(date +%s)
  elapsed=$(( now - start ))
  if [ "$elapsed" -ge "$TIMEOUT" ]; then
    echo "TIMEOUT after ${elapsed}s — still serving ${last:-unknown}"
    echo "check the build log: https://chart.amow.com is fine but Coolify may have failed"
    exit 1
  fi

  # 502 during the rolling container swap is normal; keep polling.
  got=$(curl -fsS -m 5 "$URL/api/version" 2>/dev/null \
        | sed -n 's/.*"commit"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')

  if [ "$got" = "$want" ]; then
    echo "deployed ${short} after ${elapsed}s"
    exit 0
  fi

  if [ "$got" != "$last" ]; then
    echo "  ${elapsed}s: serving ${got:-unreachable}"
    last="$got"
  fi
  sleep 3
done
