#!/bin/bash
set -euo pipefail

method=${1:?HTTP method is required}
path=${2:?API path is required}
audit_source=${3:-unknown}
body=${4:-}
output_path=${5:-}

case "$method" in
    GET|POST|PUT|PATCH|DELETE) ;;
    *) echo "Unsupported HTTP method" >&2; exit 2 ;;
esac
case "$path" in
    /*) ;;
    *) echo "API path must start with /" >&2; exit 2 ;;
esac
if [[ "$path" == *$'\n'* || "$path" == *$'\r'* ]]; then
    echo "Invalid API path" >&2
    exit 2
fi

source /etc/wireshield/api.env
: "${HNE_API_KEY:?HNE_API_KEY is not configured}"

args=(
    curl -sk -X "$method"
    -H "Content-Type: application/json"
    -H "X-API-Key: $HNE_API_KEY"
    -H "X-Audit-Source: $audit_source"
    -w '%{http_code}'
)
if [[ -n "$body" ]]; then
    args+=(-d "$body")
fi
if [[ -n "$output_path" ]]; then
    args+=(-o "$output_path")
fi
args+=("https://127.0.0.1:8420/api/v1$path")
exec "${args[@]}"