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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
WATCH_DIR="$ROOT_DIR/kraiken-lib/src"
SERVICES=(harb_ponder_1 harb_webapp_1 harb_landing_1 harb_txn-bot_1)

if ! command -v inotifywait >/dev/null 2>&1; then
  echo "Error: inotifywait not found. Install inotify-tools." >&2
  exit 1
fi

if ! command -v docker >/dev/null 2>&1; then
  echo "Error: docker not found on PATH." >&2
  exit 1
fi

cd "$ROOT_DIR"

restart_services() {
  local missing=0
  local running
  mapfile -t running < <(docker ps --format '{{.Names}}')

  for service in "${SERVICES[@]}"; do
    local found=1
    for name in "${running[@]}"; do
      if [[ "$name" == "$service" ]]; then
        found=0
        break
      fi
    done

    if (( found != 0 )); then
      echo "Warning: $service not running; skipping restart" >&2
      missing=1
      continue
    fi

    if ! docker restart "$service" >/dev/null; then
      echo "Warning: failed to restart $service" >&2
      missing=1
    fi
  done

  if [[ $missing -eq 0 ]]; then
    echo "Services restarted"
  fi
}

inotifywait -m -r -e close_write,create,delete,moved_to,moved_from "$WATCH_DIR" |
while read -r _directory _events filename; do
  echo "kraiken-lib changed: $filename"
  ./scripts/build-kraiken-lib.sh
  restart_services || true
done
