#!/usr/bin/env bash
#
# Open the Ravin license generator page on this machine (macOS / Linux).
#
#   bash tools/license/ui.sh            # http://127.0.0.1:8099
#   PORT=8100 bash tools/license/ui.sh
#
# Optional: LICENSE_STORE=/path/to/licenses   (default: <repo>/licenses or <bundle>/licenses)
#           IONCUBE_ENCODER=/path/to/ioncube_encoder
#
# Binds 127.0.0.1 only and the page refuses any other client. On a remote
# server, reach it through an SSH tunnel:
#   ssh -L 8099:127.0.0.1:8099 user@server     then open http://127.0.0.1:8099
#
# Vendor tool: it holds the plain signing key. Run it only on machines you
# control, never on a customer's server.
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORT="${PORT:-8099}"
URL="http://127.0.0.1:${PORT}/"

install_dir="${CONFIG_INSTALL_DIR:-/opt/awareness}"
if [[ -f "${install_dir}/docker-compose.yml" && "${LICENSE_UI_ALLOW_ON_INSTALL:-}" != "1" ]]; then
    echo "error: this machine runs a Ravin installation (${install_dir})." >&2
    echo "       The generator holds the signing key and must not live on a customer server." >&2
    echo "       If this is YOUR OWN server, re-run with LICENSE_UI_ALLOW_ON_INSTALL=1." >&2
    exit 1
fi

if ! command -v php >/dev/null 2>&1; then
    echo "error: PHP is not installed. Install PHP 8.1+ (CLI), or use the Docker launcher:" >&2
    echo "       bash ${DIR}/docker/docker-run.sh" >&2
    exit 1
fi

echo "Ravin license generator → ${URL}  (Ctrl+C to stop)"
if [[ -n "${SSH_CONNECTION:-}" ]]; then
    echo "Remote session: on your own computer run  ssh -L ${PORT}:127.0.0.1:${PORT} $(whoami)@$(hostname)"
    echo "then open ${URL} there."
elif [[ "${NO_OPEN:-}" != "1" ]]; then
    if command -v open >/dev/null 2>&1; then
        ( sleep 1; open "$URL" ) &
    elif command -v xdg-open >/dev/null 2>&1; then
        ( sleep 1; xdg-open "$URL" >/dev/null 2>&1 ) &
    fi
fi

exec php -d display_errors=0 -d log_errors=1 -d upload_max_filesize=1M -d post_max_size=2M \
    -S "127.0.0.1:${PORT}" -t "${DIR}/ui" "${DIR}/ui/index.php"
