#!/usr/bin/env bash
# rmm-auth.sh - Get GuruRMM authentication token
# Outputs: TOKEN RMM_URL REPO_ROOT (space-separated)
# Usage: eval "$(bash .claude/scripts/rmm-auth.sh)"
#   This sets: $TOKEN, $RMM, $REPO_ROOT in the calling shell

set -euo pipefail

# Resolve paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
IDENTITY_FILE="$REPO_ROOT/.claude/identity.json"

# Functional-error logger. MUST stay silent on stdout (this script's stdout is
# eval'd by the caller) — log-skill-error.sh prints only to stderr, and we
# redirect everything to /dev/null to be safe.
_logerr() { bash "$REPO_ROOT/.claude/scripts/log-skill-error.sh" "rmm-auth" "$@" >/dev/null 2>&1 || true; }

if [ ! -f "$IDENTITY_FILE" ]; then
    _logerr "identity.json not found; RMM auth cannot resolve vault" --context "path=$IDENTITY_FILE"
    echo "export TOKEN=''; export RMM=''; export REPO_ROOT=''; echo '[ERROR] identity.json not found' >&2"
    exit 1
fi

VAULT_PATH=$(jq -r '.vault_path // empty' "$IDENTITY_FILE")
if [ -z "$VAULT_PATH" ]; then
    _logerr "vault_path not in identity.json; RMM auth failed" --context "path=$IDENTITY_FILE"
    echo "export TOKEN=''; export RMM=''; export REPO_ROOT=''; echo '[ERROR] vault_path not in identity.json' >&2"
    exit 1
fi

VAULT_SH="$VAULT_PATH/scripts/vault.sh"
if [ ! -f "$VAULT_SH" ]; then
    _logerr "vault.sh not found at resolved vault_path; RMM auth failed" --context "path=$VAULT_SH"
    echo "export TOKEN=''; export RMM=''; export REPO_ROOT=''; echo '[ERROR] vault.sh not found at $VAULT_SH' >&2"
    exit 1
fi

RMM_URL="http://172.16.3.30:3001"

# Get credentials
RMM_EMAIL=$(bash "$VAULT_SH" get-field infrastructure/gururmm-server.sops.yaml credentials.gururmm-api.admin-email 2>/dev/null)
RMM_PASS=$(bash "$VAULT_SH" get-field infrastructure/gururmm-server.sops.yaml credentials.gururmm-api.admin-password 2>/dev/null)

if [ -z "$RMM_EMAIL" ] || [ -z "$RMM_PASS" ]; then
    _logerr "vault read of GuruRMM API credentials failed (empty email/password)" --context "entry=infrastructure/gururmm-server.sops.yaml"
    echo "export TOKEN=''; export RMM=''; export REPO_ROOT=''; echo '[ERROR] Failed to get RMM credentials from vault' >&2"
    exit 1
fi

# Login - use jq to build JSON safely
PAYLOAD=$(jq -n --arg email "$RMM_EMAIL" --arg password "$RMM_PASS" '{email: $email, password: $password}')
JWT=$(curl -s -X POST "$RMM_URL/api/auth/login" -H "Content-Type: application/json" -d "$PAYLOAD")
TOKEN=$(echo "$JWT" | jq -r '.token // empty')

if [ -z "$TOKEN" ]; then
    _logerr "RMM login failed (no token returned from /api/auth/login)" --context "url=$RMM_URL resp=${JWT:0:80}"
    echo "export TOKEN=''; export RMM=''; export REPO_ROOT=''; echo '[ERROR] RMM login failed: $JWT' >&2"
    exit 1
fi

# Output exports for eval
echo "export TOKEN='$TOKEN'"
echo "export RMM='$RMM_URL'"
echo "export REPO_ROOT='$REPO_ROOT'"
echo "echo '[OK] Authenticated to GuruRMM' >&2"
