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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# shellcheck disable=SC1091
. "$ROOT/scripts/configure-backoffice-https-vm.sh"

assert_rejected() {
  local label="${1:?label}" function_name="${2:?function}" value="${3:-}"
  if ("$function_name" "$value") >/dev/null 2>&1; then
    echo "FAIL: $label was accepted: $value" >&2
    exit 1
  fi
}

validate_public_host "admin.example.com"
validate_public_host "130.162.134.59"
validate_tls_email "ops@example.com"
validate_ssh_host "hermes"
validate_ipv4 "130.162.134.59"
validate_port "8082"
validate_remote_dir '$HOME/apps/vpd-backoffice'

assert_rejected "invalid IPv4 host" validate_public_host "130.162.134.999"
assert_rejected "wildcard host" validate_public_host "*.example.com"
assert_rejected "single-label host" validate_public_host "hermes"
assert_rejected "invalid email" validate_tls_email "ops at example.com"
assert_rejected "SSH option injection" validate_ssh_host "-oProxyCommand=id"
assert_rejected "invalid IPv4" validate_ipv4 "130.162.134.999"
assert_rejected "privileged overflow port" validate_port "65536"
assert_rejected "remote command injection" validate_remote_dir '$HOME/apps/x;id'
assert_rejected "remote path traversal" validate_remote_dir '$HOME/apps/../etc'

tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/vpd-backoffice-https-test.XXXXXX")"
trap 'rm -rf "$tmp_dir"' EXIT
PUBLIC_HOST="admin.example.com"
TLS_EMAIL="ops@example.com"
APP_PORT="8082"
render_caddyfile "$tmp_dir/Caddyfile"

grep -Fq 'admin.example.com {' "$tmp_dir/Caddyfile"
grep -Fq 'email ops@example.com' "$tmp_dir/Caddyfile"
grep -Fq 'reverse_proxy 127.0.0.1:8082' "$tmp_dir/Caddyfile"
grep -Fq 'Strict-Transport-Security "max-age=31536000; includeSubDomains"' "$tmp_dir/Caddyfile"

PUBLIC_HOST="130.162.134.59"
render_caddyfile "$tmp_dir/Caddyfile.ip"
grep -Fq '130.162.134.59 {' "$tmp_dir/Caddyfile.ip"
grep -Fq 'profile shortlived' "$tmp_dir/Caddyfile.ip"

echo "PASS: HTTPS configuration validation and rendering"
