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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/lib.sh"

offline_verify_backend_health() {
  local runtime_env_file="$1"
  local backend_port
  backend_port="$(offline_env_value "${runtime_env_file}" "BACKEND_PORT")"
  if [[ -z "${backend_port}" ]]; then
    echo "BACKEND_PORT missing in ${runtime_env_file}" >&2
    return 1
  fi
  curl -fsS "http://127.0.0.1:${backend_port}/health" >/dev/null
}

offline_verify_nginx_health() {
  local runtime_env_file="$1"
  local server_name listen_port
  server_name="$(offline_env_value "${runtime_env_file}" "SERVER_NAME")"
  listen_port="$(offline_env_value "${runtime_env_file}" "NGINX_LISTEN_PORT")"
  : "${listen_port:=80}"
  if [[ -z "${server_name}" ]]; then
    echo "SERVER_NAME missing in ${runtime_env_file}" >&2
    return 1
  fi
  curl -fsS -H "Host: ${server_name}" "http://127.0.0.1:${listen_port}/health" >/dev/null
}

offline_write_verify_artifact() {
  local runtime_env_file="$1"
  local mode="$2"
  local target="$3"
  local backend_ok="$4"
  local nginx_ok="$5"
  local artifact_dir
  artifact_dir="$(offline_env_value "${runtime_env_file}" "DEPLOY_ARTIFACT_DIR")"
  if [[ -z "${artifact_dir}" ]]; then
    echo "DEPLOY_ARTIFACT_DIR missing in ${runtime_env_file}" >&2
    return 1
  fi
  mkdir -p "${artifact_dir}"
  cat > "${artifact_dir}/verify.env" <<EOF
MODE=${mode}
TARGET=${target}
BACKEND_HEALTH=${backend_ok}
NGINX_HEALTH=${nginx_ok}
VERIFIED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
EOF
}

offline_write_pack_verify_placeholder() {
  local runtime_env_file="$1"
  local mode="$2"
  local target="$3"
  local artifact_dir
  artifact_dir="$(offline_env_value "${runtime_env_file}" "DEPLOY_ARTIFACT_DIR")"
  if [[ -z "${artifact_dir}" ]]; then
    echo "DEPLOY_ARTIFACT_DIR missing in ${runtime_env_file}" >&2
    return 1
  fi
  mkdir -p "${artifact_dir}"
  cat > "${artifact_dir}/pack-verify.env" <<EOF
MODE=${mode}
TARGET=${target}
PACK_VERIFY_STATUS=placeholder
PACK_VERIFY_NOTE=phase1-local-health-only
RECORDED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
EOF
}
