#!/usr/bin/env sh
set -eu

compose_file="docker/staging_pull_compose.template.yaml"

if [ ! -f "$compose_file" ]; then
  echo "missing expected file: $compose_file" >&2
  exit 1
fi

assert_service_has_restart_policy() {
  service="$1"
  awk -v service="$service" '
    $0 ~ "^    " service ":" {
      in_service = 1
      found = 0
      next
    }
    in_service && /^    [A-Za-z0-9_-]+:/ {
      exit found ? 0 : 1
    }
    in_service && /^[[:space:]]+restart:[[:space:]]+(always|unless-stopped)[[:space:]]*$/ {
      found = 1
    }
    END {
      if (in_service) {
        exit found ? 0 : 1
      }
    }
  ' "$compose_file" || {
    echo "ERROR: long-running staging service must define restart: always or restart: unless-stopped: $service" >&2
    exit 1
  }
}

assert_service_has_no_restart_policy() {
  service="$1"
  if awk -v service="$service" '
    $0 ~ "^    " service ":" {
      in_service = 1
      found = 0
      next
    }
    in_service && /^    [A-Za-z0-9_-]+:/ {
      exit found ? 0 : 1
    }
    in_service && /^[[:space:]]+restart:/ {
      found = 1
    }
    END {
      if (in_service) {
        exit found ? 0 : 1
      }
    }
  ' "$compose_file"; then
    echo "ERROR: one-shot staging service must not define restart policy: $service" >&2
    exit 1
  fi
}

for service in \
  postgres \
  clickhouse \
  redis \
  gateway \
  postgres_ory \
  kratos \
  hydra \
  keto \
  oathkeeper \
  ory_clickhouse \
  backend \
  adminfront \
  devfront \
  orgfront \
  userfront
do
  assert_service_has_restart_policy "$service"
done

for service in \
  kratos-migrate \
  hydra-migrate \
  keto-migrate \
  oathkeeper_logs_init \
  ory_stack_check \
  init-rp \
  infra_check
do
  assert_service_has_no_restart_policy "$service"
done

echo "staging pull restart policy checks passed"
