#!/bin/sh
# ghtp-node-agent-enroll — configure and start the GHTP node agent service.
set -e

CONFIG=/etc/ghtp-node-agent/config.env

usage() {
    echo "Usage: sudo ghtp-node-agent-enroll --url <control-plane-url> --token <enrollment-token> [--name <node-name>] [--insecure]"
    echo ""
    echo "  --insecure  Skip TLS certificate verification. Only for a control plane with"
    echo "              a known cert gap — never use this against an untrusted network."
    exit 1
}

if [ "$(id -u)" != "0" ]; then
    echo "Must be run as root (sudo)." >&2
    exit 1
fi

URL=""
TOKEN=""
NAME="$(hostname)"
INSECURE="0"

while [ $# -gt 0 ]; do
    case "$1" in
        --url) URL="$2"; shift 2 ;;
        --token) TOKEN="$2"; shift 2 ;;
        --name) NAME="$2"; shift 2 ;;
        --insecure) INSECURE="1"; shift ;;
        *) usage ;;
    esac
done

if [ -z "$URL" ] || [ -z "$TOKEN" ]; then
    usage
fi

if [ "$INSECURE" = "1" ]; then
    echo "[!] TLS certificate verification will be DISABLED for this node." >&2
fi

cat > "$CONFIG" <<EOF
GHTP_CONTROL_PLANE_URL=$URL
GHTP_ENROLLMENT_TOKEN=$TOKEN
GHTP_NODE_NAME=$NAME
GHTP_NODE_CONFIG=/etc/ghtp-node-agent/node.json
GHTP_INSECURE_TLS=$INSECURE
EOF
chown ghtp-node:ghtp-node "$CONFIG"
chmod 0640 "$CONFIG"

systemctl enable --now ghtp-node-agent

echo "Enrolling '$NAME' with $URL ..."
echo "Check status: systemctl status ghtp-node-agent"
echo "Follow logs:  journalctl -u ghtp-node-agent -f"
