#!/usr/bin/env bash
# Validates the prod install files before they are published to the storage
# that serves /services/prod — the source `ush platform install/update`
# downloads from. Run this on every change to docker-compose.yaml /
# services.yaml; a broken or unpublished-image compose must never reach
# the file server (a hand-patched served copy once shipped a duplicate
# YAML key that broke updates on every installed host).
#
# Checks:
#   1. docker-compose.yaml parses and is internally consistent — duplicate
#      keys, broken anchors and unresolved interpolation fail here.
#      Required secrets (${VAR:?...}) are masked with dummies so only real
#      errors surface.
#   2. Images referenced by the compose file are reported against the
#      registry. Most service images are delivered to target hosts by the
#      UP CI/CD flow (ssh deploy) and never pushed to a public registry, and
#      the local .env may pin tags that differ from published ones — so a
#      missing registry entry is a WARN, not a failure. Set STRICT_IMAGES=1
#      to enforce (useful right after adding a new service that must be
#      publishable).
#   3. services.yaml parses as YAML (needs python3 + PyYAML; skipped with
#      a warning otherwise).
#
# Usage:
#   devops/prod/validate-install-files.sh                 # all checks
#   SKIP_IMAGES=1 devops/prod/validate-install-files.sh   # offline: skip registry lookups
#   STRICT_IMAGES=1 devops/prod/validate-install-files.sh # missing registry image = failure
#
# Exit codes: 0 — ok, 1 — validation failed.
set -euo pipefail
cd "$(dirname "$0")"

fail=0

# --- 1. compose parse -------------------------------------------------------
# Extract required vars (${KEY:?message}) and mask them for config.
required="$(grep -oE '\$\{[A-Z_][A-Z0-9_]*:\?' docker-compose.yaml \
  | sed -E 's/^\$\{//; s/:\?$//' | sort -u || true)"
for key in $required; do
  export "$key=validation-dummy"
done

echo "==> docker compose config"
if out="$(docker compose --profile migrate config -q 2>&1)"; then
  echo "OK   docker-compose.yaml parses (including migrate profile)"
else
  echo "FAIL docker-compose.yaml: ${out}"
  fail=1
fi

# --- 2. images exist in registry --------------------------------------------
if [[ "${SKIP_IMAGES:-0}" == "1" ]]; then
  echo "SKIP image check (SKIP_IMAGES=1)"
else
  echo "==> registry image check"
  images="$(docker compose --profile migrate config --images 2>/dev/null \
    || docker compose --profile migrate config | awk '/^[[:space:]]+image:/ {print $2}')"
  sorted="$(printf '%s\n' "$images" | sort -u)"
  missing=0
  while IFS= read -r img; do
    [[ -z "$img" ]] && continue
    if docker manifest inspect "$img" >/dev/null 2>&1; then
      echo "OK    $img"
    else
      echo "WARN  $img — not in the public registry (ok if UP CI/CD delivers it to target hosts; bad if fresh installs must pull it)"
      missing=$((missing + 1))
    fi
  done <<< "$sorted"
  if [[ "$missing" != "0" ]]; then
    if [[ "${STRICT_IMAGES:-0}" == "1" ]]; then
      echo "FAIL  $missing image(s) not found in registry (STRICT_IMAGES=1)"
      fail=1
    else
      echo "NOTE  $missing image(s) not in the public registry — set STRICT_IMAGES=1 to enforce"
    fi
  fi
fi

# --- 3. services.yaml --------------------------------------------------------
echo "==> services.yaml"
if command -v python3 >/dev/null 2>&1 && python3 -c 'import yaml' >/dev/null 2>&1; then
  if python3 -c 'import yaml, sys; yaml.safe_load(open("services.yaml"))'; then
    echo "OK   services.yaml parses"
  else
    echo "FAIL services.yaml is not valid YAML"
    fail=1
  fi
else
  echo "WARN python3 + PyYAML unavailable — services.yaml not validated"
fi

if [[ "$fail" != "0" ]]; then
  echo
  echo "VALIDATION FAILED — do not publish these files to /services/prod."
fi
exit "$fail"
