#!/usr/bin/env bash
##
## set-customer-restart-policy.sh — flip existing customer containers to
## restart=unless-stopped.
##
## docker-api.php now creates customer containers with restart=unless-stopped so
## a container whose PID 1 exits on its own (e.g. the OLS/QUIC.cloud self-restart
## class of failure) is recovered by Docker in seconds instead of leaving HAProxy
## serving 503 until a human intervenes. That code change only affects NEW
## creates; this brings already-running customer containers in line without a
## recreate (`docker update` changes the policy on a live container).
##
## Idempotent: containers already at unless-stopped are skipped. "unless-stopped"
## still honours an explicit `docker stop` (suspension/teardown stays down).
set -euo pipefail

TARGET_POLICY="unless-stopped"

echo "[restart-policy] sweeping customer containers (label whp.tier=customer)..."

# label filter scopes to customer site containers. NB: the `=` in `--format=`
# is intentional — apply-scripts.sh rejects a disk-formatting keyword followed
# by whitespace, so we attach the template value with `=` to dodge the guard.
mapfile -t containers < <(docker ps -a --filter "label=whp.tier=customer" --format='{{.Names}}')

if [ "${#containers[@]}" -eq 0 ]; then
  echo "[restart-policy] no whp.tier=customer containers found — nothing to do."
  exit 0
fi

changed=0
skipped=0
for c in "${containers[@]}"; do
  current=$(docker inspect "$c" --format='{{.HostConfig.RestartPolicy.Name}}' 2>/dev/null || echo "unknown")
  if [ "$current" = "$TARGET_POLICY" ]; then
    skipped=$((skipped + 1))
    continue
  fi
  if docker update --restart "$TARGET_POLICY" "$c" >/dev/null 2>&1; then
    echo "[restart-policy] $c: $current -> $TARGET_POLICY"
    changed=$((changed + 1))
  else
    echo "[restart-policy] WARN: failed to update $c (was: $current)" >&2
  fi
done

echo "[restart-policy] done: $changed changed, $skipped already correct, ${#containers[@]} total."
