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

: "${BASE_URL:?Set BASE_URL to the deployed HTTPS origin, for example https://finance.example.com}"

base_url="${BASE_URL%/}"
if [[ "${base_url}" != https://* ]]; then
    echo "BASE_URL must use HTTPS." >&2
    exit 2
fi

headers_file="$(mktemp)"
trap 'rm -f "${headers_file}"' EXIT

curl --fail --silent --show-error --connect-timeout 10 --max-time 20 \
    "${base_url}/up" >/dev/null

login_status="$(curl --silent --show-error --connect-timeout 10 --max-time 20 \
    --dump-header "${headers_file}" --output /dev/null --write-out '%{http_code}' \
    "${base_url}/login")"

if [[ "${login_status}" != "200" ]]; then
    echo "Expected /login to return HTTP 200, got ${login_status}." >&2
    exit 1
fi

require_header() {
    local pattern="$1"
    local description="$2"

    if ! grep -Eiq "${pattern}" "${headers_file}"; then
        echo "Missing or invalid ${description} header on /login." >&2
        exit 1
    fi
}

require_header '^strict-transport-security:[[:space:]].*max-age=' 'Strict-Transport-Security'
require_header '^content-security-policy:' 'Content-Security-Policy'
require_header '^x-content-type-options:[[:space:]]*nosniff' 'X-Content-Type-Options'
require_header '^x-frame-options:[[:space:]]*deny' 'X-Frame-Options'
require_header '^referrer-policy:[[:space:]]*strict-origin-when-cross-origin' 'Referrer-Policy'

printf 'Release HTTP smoke check passed for %s\n' "${base_url}"
