#!/usr/bin/env bash
# Evomedia.net Token Savers — https://github.com/kellymichels/zscripts-token-savers
# Created by Kelly Michels · dev@evomedia.net
# Licensed under the MIT License. See LICENSE.
#
# zrepair — audit and repair container/proxy routing on the server, then smoke test.
#
# Usage:
#   zrepair <project> [<project> ...]
#
# For each project: shows compose status, starts the stack if it's down,
# validates the edge proxy's nginx config (once, if an edge project is defined),
# and smoke-tests the live domain.

set -uo pipefail
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/zhelpers.sh"
z_track_start "$@"
z_need_config
z_require ssh curl

if [ $# -eq 0 ]; then
  printf '\n'; warn "Usage: zrepair <project> [<project> ...]"
  dim "  Projects in zconfig.json: $(zproj_csv)"
  exit 1
fi

HOST="$(zec2_ip)"

printf '\n'; info "=== Routing repair & diagnostics ==="
dim "Target host: $HOST"

# Validate the edge proxy config once up front, if one is defined.
EDGE_KEY="$(zedge_key)"
if [ -n "$EDGE_KEY" ]; then
  pc="$(zproj "$EDGE_KEY" .proxyContainer)"
  if [ -n "$pc" ]; then
    printf '\n'; warn "  [edge] Validating nginx config in proxy container '$pc'..."
    zec2_step "nginx -t in $pc" "sudo docker exec $pc nginx -t 2>&1" || exit 1
  fi
fi

for key in "$@"; do
  zproj_require "$key"
  label="$(zproj "$key" .label)"; [ -n "$label" ] || label="$key"
  compose_dir="$(zremote_compose_dir "$key")"
  domain="$(zproj "$key" .domain)"

  printf '\n'
  info "========================================="
  info "=== Repairing $label ($key) ==="
  info "========================================="
  printf '\n'

  warn "  [1/3] Compose status on the server..."
  zec2_step "Check compose status" \
    "cd $compose_dir || exit 1; echo 'Running containers:'; sudo docker compose ps" || exit 1

  warn "  [2/3] Ensuring stack is up..."
  zec2_step "Ensure stack is up" \
    "cd $compose_dir || exit 1; if ! sudo docker compose ps | grep -q Up; then echo '    [Action] Stack is down. Starting...'; sudo docker compose up -d; else echo '    [OK] Stack is active and UP.'; fi" || exit 1

  if [ -n "$domain" ]; then
    warn "  [3/3] Smoke test for https://$domain..."
    code="$(http_code "http://$HOST/" "$domain")"
    if [ "$code" = "000" ]; then
      err "    FAIL - smoke test failed: no HTTP response"
    elif [ "$code" -lt 400 ]; then
      ok "    PASS - responded with HTTP $code (Online)"
    elif [ "$code" -lt 500 ]; then
      ok "    PASS - responded with HTTP $code (Online/Redirect or auth)"
    else
      warn "    WARNING - unexpected HTTP $code"
    fi
  else
    warn "  [3/3] No domain configured - skipping smoke test."
  fi
done

printf '\n'; ok "=== Repair & diagnostics completed ==="
printf '\n'
