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

HOST="$1"
STACK="${2:-}"
BASE="/opt/services"

cd "$BASE"

if [ -n "$STACK" ]; then
  dirs="$STACK"
else
  dirs="$(find "$HOST" -mindepth 2 -maxdepth 2 -name docker-compose.yml | cut -d/ -f2 | sort -u)"

  # Remove stale stacks whose directories were deleted from the repo
  stale_dirs="$(docker ps -a \
    --filter "label=com.docker.compose.project.working_dir" \
    --format '{{.Label "com.docker.compose.project.working_dir"}}' \
    | sort -u \
    | grep "^$BASE/$HOST/" || true)"

  for working_dir in $stale_dirs; do
    dir="${working_dir#"$BASE/$HOST/"}"
    dir="${dir%%/*}"
    if [ ! -f "$BASE/$HOST/$dir/docker-compose.yml" ]; then
      echo "==> Removing stale stack: $dir"
      containers="$(docker ps -aq --filter "label=com.docker.compose.project.working_dir=$working_dir" || true)"
      [ -n "$containers" ] && docker rm -f $containers
      networks="$(docker network ls -q --filter "label=com.docker.compose.project.working_dir=$working_dir" || true)"
      [ -n "$networks" ] && docker network rm $networks || true
    fi
  done
fi

if [ -z "$dirs" ]; then
  echo "No stacks found for $HOST"
  exit 0
fi

failed=""

for dir in $dirs; do
  echo "==> Stack: $dir"

  if [ "$dir" = "gitea-runner" ]; then
    echo "Skipping gitea-runner (self-update not safe from CI)"
    continue
  fi

  if { [ "$HOST" = "cloud-pc" ] || [ "$HOST" = "mini-pc" ]; } && [ "$dir" = "zerotier" ]; then
    echo "Skipping zerotier (managed by NixOS service)"
    continue
  fi

  stack_dir="$BASE/$HOST/$dir"
  cd "$stack_dir"

  if [ ! -f docker-compose.yml ]; then
    echo "No docker-compose.yml, skipping"
    cd "$BASE"
    continue
  fi

  docker compose config --quiet

  # Remove containers whose container_name matches this stack but belong to a different project.
  # docker compose down won't touch them because they carry no matching project labels.
  while IFS= read -r cname; do
    [ -z "$cname" ] && continue
    existing="$(docker ps -aq --filter "name=^/${cname}$" 2>/dev/null || true)"
    [ -z "$existing" ] && continue
    owner="$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project.working_dir"}}' "$existing" 2>/dev/null || true)"
    if [ "$owner" != "$(pwd)" ]; then
      echo "==> Removing conflicting container $cname (owner: ${owner:-none})"
      docker rm -f "$existing"
    fi
  done < <(docker compose config 2>/dev/null | awk '/^[[:space:]]+container_name:/{gsub(/["'"'"']/, "", $2); print $2}')

  if grep -qE '^[[:space:]]*build:' docker-compose.yml; then
    docker compose up -d --build --remove-orphans
  else
    docker compose pull
    docker compose up -d --remove-orphans
  fi

  # Health check: give containers a moment, then fail on crashed services
  sleep 5
  docker compose ps
  if docker compose ps 2>&1 | grep -qE 'Exited \([1-9]|Restarting'; then
    docker compose logs --tail=30
    echo "ERROR: Service failure in stack $dir"
    failed="$failed $dir"
  fi

  cd "$BASE"
done

if [ -n "$failed" ]; then
  echo "FAILED stacks:$failed"
  exit 1
fi
