#!/bin/sh
# Install the oikos-web deploy-webhook launchd unit on the mac-mini.
#
# Renders scripts/oikos-web-deploy-webhook.plist with real secret values and
# loads it. Values come from env; when absent, the HMAC secret and API token
# are resolved from the oikos stack's Infisical via the oikos CLI (only
# available on the mac-mini with the oikos checkout + .env).
#
# Usage:
#   WEBHOOK_HMAC_SECRET=... GITEA_TOKEN=... ./scripts/install-webhook.sh
set -e

REPO_DIR="${REPO_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
PLIST_DST="$HOME/Library/LaunchAgents/network.hubris.oikos-web-deploy-webhook.plist"
LABEL="network.hubris.oikos-web-deploy-webhook"

OIKOS_CLI="${OIKOS_CLI:-$HOME/Projects/oikos/oikos}"
infisical_get() {
    [ -x "$OIKOS_CLI" ] || return 1
    (cd "$HOME/Projects/oikos" && set -a && . ./.env 2>/dev/null && set +a \
        && OIKOS_INFISICAL_SITE_URL=http://localhost:8080 "$OIKOS_CLI" secret get "$1" 2>/dev/null) \
        | grep -v '^{' | grep -v '^$' | head -n1
}

HMAC="${WEBHOOK_HMAC_SECRET:-$(infisical_get webhook_hmac-secret || true)}"
GITEA_TOKEN="${GITEA_TOKEN:-$(infisical_get gitea-pat_token || true)}"
API_TOKEN="${OIKOS_API_TOKEN:-$(infisical_get api_token || true)}"

if [ -z "$HMAC" ]; then
    echo "ERROR: WEBHOOK_HMAC_SECRET not set and could not resolve from Infisical" >&2
    exit 1
fi

# Build the webhook binary first
(cd "$REPO_DIR" && make webhook)

launchctl bootout "gui/$(id -u)" "$PLIST_DST" 2>/dev/null || true

cat > "$PLIST_DST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>$LABEL</string>
    <key>ProgramArguments</key>
    <array>
        <string>$REPO_DIR/webhook</string>
    </array>
    <key>WorkingDirectory</key>
    <string>$REPO_DIR</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>HOME</key>
        <string>$HOME</string>
        <key>PATH</key>
        <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        <key>WEBHOOK_LISTEN</key>
        <string>:9798</string>
        <key>WEBHOOK_REPO_DIR</key>
        <string>$REPO_DIR</string>
        <key>WEBHOOK_HMAC_SECRET</key>
        <string>$HMAC</string>
        <key>GITEA_URL</key>
        <string>https://git.hubris.network</string>
        <key>GITEA_TOKEN</key>
        <string>$GITEA_TOKEN</string>
        <key>OIKOS_API_TOKEN</key>
        <string>$API_TOKEN</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>$HOME/Library/Logs/oikos-web-webhook.log</string>
    <key>StandardErrorPath</key>
    <string>$HOME/Library/Logs/oikos-web-webhook.log</string>
</dict>
</plist>
EOF
chmod 600 "$PLIST_DST"

launchctl bootstrap "gui/$(id -u)" "$PLIST_DST"
sleep 1
launchctl print "gui/$(id -u)/$LABEL" >/dev/null && echo "installed: $LABEL (listening :9798)"
