#!/usr/bin/env sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
TEMPLATE="$SCRIPT_DIR/nginx-bmcli.conf.template"
LISTEN="127.0.0.1:8443"
UPSTREAM="127.0.0.1:8080"
SERVER_NAME="localhost"
CERTIFICATE=""
PRIVATE_KEY=""
OUTPUT="./bmcli-nginx.conf"
INSTALL=0

usage() {
    cat <<'EOF'
Usage: configure-nginx.sh --certificate FILE --private-key FILE [options]

Options:
  --listen ADDRESS:PORT      TLS listener (default: 127.0.0.1:8443)
  --upstream ADDRESS:PORT    BMCLI loopback listener (default: 127.0.0.1:8080)
  --server-name NAME         TLS server name (default: localhost)
  --output FILE              Rendered configuration path
  --install                  Install as /etc/nginx/conf.d/bmcli.conf and reload
  --help                     Show this help
EOF
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        --certificate) CERTIFICATE=${2-}; shift 2 ;;
        --private-key) PRIVATE_KEY=${2-}; shift 2 ;;
        --listen) LISTEN=${2-}; shift 2 ;;
        --upstream) UPSTREAM=${2-}; shift 2 ;;
        --server-name) SERVER_NAME=${2-}; shift 2 ;;
        --output) OUTPUT=${2-}; shift 2 ;;
        --install) INSTALL=1; shift ;;
        --help|-h) usage; exit 0 ;;
        *) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
    esac
done

if [ ! -f "$TEMPLATE" ]; then
    echo "Nginx template not found: $TEMPLATE" >&2
    exit 1
fi
if [ ! -f "$CERTIFICATE" ] || [ ! -f "$PRIVATE_KEY" ]; then
    echo "Both --certificate and --private-key must name existing files." >&2
    exit 2
fi
case "$LISTEN:$UPSTREAM" in
    *[!A-Za-z0-9.:_-]*) echo "Listener and upstream contain unsupported characters." >&2; exit 2 ;;
esac
case "$SERVER_NAME" in
    *[!A-Za-z0-9._-]*) echo "Server name contains unsupported characters." >&2; exit 2 ;;
esac

CERTIFICATE=$(CDPATH= cd -- "$(dirname -- "$CERTIFICATE")" && pwd)/$(basename -- "$CERTIFICATE")
PRIVATE_KEY=$(CDPATH= cd -- "$(dirname -- "$PRIVATE_KEY")" && pwd)/$(basename -- "$PRIVATE_KEY")

escape_sed() {
    printf '%s' "$1" | sed 's/[&|]/\\&/g'
}

mkdir -p "$(dirname -- "$OUTPUT")"
sed \
    -e "s|__LISTEN__|$(escape_sed "$LISTEN")|g" \
    -e "s|__UPSTREAM__|$(escape_sed "$UPSTREAM")|g" \
    -e "s|__SERVER_NAME__|$(escape_sed "$SERVER_NAME")|g" \
    -e "s|__CERTIFICATE__|$(escape_sed "$CERTIFICATE")|g" \
    -e "s|__PRIVATE_KEY__|$(escape_sed "$PRIVATE_KEY")|g" \
    "$TEMPLATE" > "$OUTPUT"
chmod 0600 "$OUTPUT"

if [ "$INSTALL" -eq 1 ]; then
    if [ "$(id -u)" -ne 0 ]; then
        echo "--install requires root privileges." >&2
        exit 2
    fi
    command -v nginx >/dev/null 2>&1 || {
        echo "nginx is required for --install." >&2
        exit 2
    }
    install -m 0600 "$OUTPUT" /etc/nginx/conf.d/bmcli.conf
    nginx -t
    if command -v systemctl >/dev/null 2>&1; then
        systemctl reload nginx
    else
        nginx -s reload
    fi
fi

printf 'Rendered BMCLI HTTPS proxy: %s\n' "$OUTPUT"
