#!/usr/bin/env bash
# install-htpasswd.sh — render /etc/nginx/htpasswd/ui-dashboard from env + reload nginx.
#
# Env (required): BASIC_AUTH_USER, BASIC_AUTH_PASS
# Env (optional): HTPASSWD_PATH (default /etc/nginx/htpasswd/ui-dashboard)
set -euo pipefail

: "${BASIC_AUTH_USER:?BASIC_AUTH_USER required}"
: "${BASIC_AUTH_PASS:?BASIC_AUTH_PASS required}"
HTPASSWD_PATH="${HTPASSWD_PATH:-/etc/nginx/htpasswd/ui-dashboard}"

# Use openssl APR1 hash (htpasswd from apache2-utils not always present).
# Format: <user>:<hash>
HASH=$(openssl passwd -apr1 "$BASIC_AUTH_PASS")

sudo mkdir -p "$(dirname "$HTPASSWD_PATH")"
echo "${BASIC_AUTH_USER}:${HASH}" | sudo tee "$HTPASSWD_PATH" >/dev/null
sudo chmod 644 "$HTPASSWD_PATH"

sudo nginx -t
sudo nginx -s reload

echo "ok: $HTPASSWD_PATH installed, nginx reloaded"
