#!/usr/bin/env bash
# setup-billing.sh — interactive billing enablement for cmon-telemetry.
#
# Assumes clustercontrol-proxy and clustercontrol-telemetry packages are
# installed and that cmon-proxy is co-located on the same host. Walks the
# operator through:
#
#   1. Provisioning the service-user + service-token across every
#      controller in ccmgr.yaml (via `ccmgradm serviceauth-bootstrap`).
#   2. Setting signing_key / api_token / billing.* in
#      /etc/cmon-telemetry/config.yaml.
#   3. Flipping billing_enabled + wiring cmon_telemetry_url / token in
#      cmon-proxy's ccmgr.yaml (via `ccmgradm init --set`).
#   4. Reloading cmon-proxy and restarting cmon-telemetry.
#   5. Verifying the plumbing end-to-end.
#
# Idempotent: a second run preserves the signing_key, api_token, and any
# operator edits to the cmon-telemetry URL. The service token IS rotated
# on re-run (intentional — that's the documented rotation path).
#
# Usage (installed):
#   sudo cmon-setup-billing [--admin-user U] [--admin-password P]
#                                     [--name NAME] [--no-api-token] [-y] [--help]
#
# Usage (source tree):
#   sudo ./scripts/setup-billing.sh [...same flags...]
#
# Environment overrides (read when the matching flag is absent):
#   CMON_ADMIN_USER          cmon admin username (for createUser RPC)
#   CCMGR_ADMIN_PASSWORD     cmon admin password (matches ccmgradm's own env-var name)

set -euo pipefail

# ---------- printf helpers ----------------------------------------------------
log()  { printf '\033[1;34m[setup-billing]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[setup-billing]\033[0m %s\n' "$*" >&2; }
die()  { printf '\033[1;31m[setup-billing]\033[0m %s\n' "$*" >&2; exit 1; }
ok()   { printf '\033[1;32m[setup-billing]\033[0m %s\n' "$*"; }

# ---------- constants --------------------------------------------------------
TELEMETRY_CONFIG="/etc/cmon-telemetry/config.yaml"
CCMGR_YAML="/usr/share/ccmgr/ccmgr.yaml"
TOKEN_DIR="/usr/share/ccmgr/service-tokens"
KEY_DIR="/usr/share/ccmgr/service-users"

CMON_PROXY_URL="https://127.0.0.1:19051"
CMON_TELEMETRY_REST="http://127.0.0.1:9520"

# ---------- arg parsing ------------------------------------------------------
ADMIN_USER=""
ADMIN_PASSWORD=""
NAME="cmon-telemetry"
GENERATE_API_TOKEN=1
ASSUME_YES=0

usage() {
    sed -n '2,/^$/p' "$0" | sed 's/^# \{0,1\}//'
    exit 0
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --admin-user)     ADMIN_USER="$2"; shift 2 ;;
        --admin-password) ADMIN_PASSWORD="$2"; shift 2 ;;
        --name)           NAME="$2"; shift 2 ;;
        --no-api-token)   GENERATE_API_TOKEN=0; shift ;;
        -y|--yes)         ASSUME_YES=1; shift ;;
        -h|--help)        usage ;;
        *) die "unknown argument: $1 (use --help)" ;;
    esac
done

# Fall back to env vars for sensitive values so they don't have to land on
# the shell-history line. CCMGR_ADMIN_PASSWORD matches ccmgradm's own
# documented convention; CMON_ADMIN_USER is local to this script.
[[ -z $ADMIN_USER     ]] && ADMIN_USER="${CMON_ADMIN_USER:-}"
[[ -z $ADMIN_PASSWORD ]] && ADMIN_PASSWORD="${CCMGR_ADMIN_PASSWORD:-}"

# ---------- preflight --------------------------------------------------------
[[ $EUID -eq 0 ]]                 || die "must run as root"
command -v ccmgradm >/dev/null    || die "ccmgradm not on PATH — install clustercontrol-proxy first"
command -v openssl  >/dev/null    || die "openssl required for key generation"
command -v curl     >/dev/null    || die "curl required for verification"
[[ -f $TELEMETRY_CONFIG ]]        || die "$TELEMETRY_CONFIG missing — install clustercontrol-telemetry first"
[[ -f $CCMGR_YAML ]]              || die "$CCMGR_YAML missing — initialise cmon-proxy first (\`ccmgradm init\`)"

if ! systemctl is-active --quiet cmon-proxy; then
    warn "cmon-proxy service is not active — bootstrap and ccmgradm both work against a stopped daemon, but the final reload will fall back to a systemctl restart"
fi

if ! grep -qE '^[[:space:]]*-[[:space:]]+url:' "$CCMGR_YAML"; then
    warn "no controllers found under instances[] in $CCMGR_YAML — bootstrap will not create any cmon-side users. Register controllers first with \`ccmgradm addcontroller …\`."
fi

# ---------- gather inputs ----------------------------------------------------
if [[ -z $ADMIN_USER ]]; then
    read -rp "cmon admin user (used to provision the service user on every controller): " ADMIN_USER
    [[ -n $ADMIN_USER ]] || die "admin user required"
fi

if [[ -z $ADMIN_PASSWORD ]]; then
    read -rsp "cmon admin password for ${ADMIN_USER}: " ADMIN_PASSWORD
    echo
    [[ -n $ADMIN_PASSWORD ]] || die "admin password required"
fi

cat <<EOF

About to enable billing on this host:

  cmon-telemetry config : $TELEMETRY_CONFIG
  cmon-proxy config     : $CCMGR_YAML
  Service token name    : $NAME
  Token hint file       : $TOKEN_DIR/$NAME
  Service user keyfile  : $KEY_DIR/$NAME.key
  cmon admin user       : $ADMIN_USER (uniform across all controllers in instances[])
  Generate api_token    : $([[ $GENERATE_API_TOKEN -eq 1 ]] && echo yes || echo no)

This will:
  1. Provision a service-user + service-token on every cmon controller.
  2. Set signing_key / billing.enabled / billing.cmon_proxy.url / .insecure in $TELEMETRY_CONFIG.
$([[ $GENERATE_API_TOKEN -eq 1 ]] && echo "  3. Generate cmon-telemetry api_token and wire it into cmon-proxy's cmon_telemetry_token.")
  $([[ $GENERATE_API_TOKEN -eq 1 ]] && echo "4. Flip billing_enabled, cmon_telemetry_url in $CCMGR_YAML." || echo "3. Flip billing_enabled, cmon_telemetry_url in $CCMGR_YAML.")
  $([[ $GENERATE_API_TOKEN -eq 1 ]] && echo "5. Reload cmon-proxy + restart cmon-telemetry; verify the plumbing." || echo "4. Reload cmon-proxy + restart cmon-telemetry; verify the plumbing.")

Existing signing_key / api_token / cmon_telemetry_url overrides are preserved
on re-run; only empty/default values are written.

EOF

if [[ $ASSUME_YES -eq 0 ]]; then
    read -rp "Proceed? [y/N] " ans
    [[ "${ans,,}" =~ ^(y|yes)$ ]] || die "cancelled"
fi

# ---------- step 1: provision service-user + service-token ------------------
log "running ccmgradm serviceauth-bootstrap (this provisions the cmon-side user on every controller in $CCMGR_YAML)"
mkdir -p "$KEY_DIR" "$TOKEN_DIR"

set +e
CCMGR_ADMIN_PASSWORD="$ADMIN_PASSWORD" \
    ccmgradm serviceauth-bootstrap \
        --name "$NAME" \
        --admin-user "$ADMIN_USER"
bootstrap_rc=$?
set -e

if [[ $bootstrap_rc -ne 0 ]]; then
    warn "ccmgradm serviceauth-bootstrap exited $bootstrap_rc — some controllers reported failures above"
    if [[ $ASSUME_YES -eq 0 ]]; then
        read -rp "Continue with whichever controllers succeeded? [y/N] " ans
        [[ "${ans,,}" =~ ^(y|yes)$ ]] || die "aborted after bootstrap failure"
    else
        warn "-y was passed; continuing despite bootstrap failures"
    fi
fi

[[ -s "$TOKEN_DIR/$NAME" ]] || die "$TOKEN_DIR/$NAME missing or empty after bootstrap — cannot continue"
TOKEN="$(< "$TOKEN_DIR/$NAME")"

# ---------- step 2: cmon-telemetry config edits -----------------------------
log "editing $TELEMETRY_CONFIG"

# Helper: get the current value of a top-level scalar key (strips wrapping
# quotes). Empty if absent or commented out.
yaml_top_value() {
    local key="$1" file="$2"
    awk -v k="$key" '
        $0 ~ "^"k":" {
            sub("^"k":[[:space:]]*", "")
            sub("^\"", ""); sub("\"$", "")
            print
            exit
        }' "$file"
}

# Helper: set a top-level scalar key. If the key exists (commented or not),
# replace its line; otherwise append. `preserve_if_set` skips the write when
# the existing value is non-empty.
set_top_key() {
    local key="$1" value="$2" preserve_if_set="${3:-0}" file="$TELEMETRY_CONFIG"
    local current
    current="$(yaml_top_value "$key" "$file")"
    if [[ $preserve_if_set -eq 1 && -n $current ]]; then
        log "  preserving existing $key (already set)"
        return
    fi
    if grep -qE "^${key}:" "$file"; then
        sed -i.bak -E "s|^${key}:.*|${key}: \"${value}\"|" "$file" && rm -f "$file.bak"
    elif grep -qE "^# ${key}:" "$file"; then
        sed -i.bak -E "s|^# ${key}:.*|${key}: \"${value}\"|" "$file" && rm -f "$file.bak"
    else
        printf '\n%s: "%s"\n' "$key" "$value" >> "$file"
    fi
    log "  set $key"
}

# signing_key — preserve on re-run
if [[ -z "$(yaml_top_value signing_key "$TELEMETRY_CONFIG")" ]]; then
    SIGNING_KEY="$(openssl rand -hex 32)"
    set_top_key signing_key "$SIGNING_KEY" 0
else
    log "  preserving existing signing_key (already set)"
fi

# api_token — preserve on re-run; skip generation when --no-api-token
API_TOKEN=""
if [[ $GENERATE_API_TOKEN -eq 1 ]]; then
    API_TOKEN="$(yaml_top_value api_token "$TELEMETRY_CONFIG")"
    if [[ -z $API_TOKEN ]]; then
        API_TOKEN="$(openssl rand -hex 32)"
        set_top_key api_token "$API_TOKEN" 0
    else
        log "  preserving existing api_token (already set)"
    fi
fi

# billing.enabled — flip false → true. Anchored on the indented line so
# there's no ambiguity with any other `enabled:` key in the file.
if grep -qE '^[[:space:]]+enabled:[[:space:]]*false' "$TELEMETRY_CONFIG"; then
    sed -i.bak -E 's|^([[:space:]]+)enabled:[[:space:]]*false|\1enabled: true|' "$TELEMETRY_CONFIG" && rm -f "$TELEMETRY_CONFIG.bak"
    log "  set billing.enabled: true"
else
    log "  preserving existing billing.enabled (already true or hand-edited)"
fi

# billing.cmon_proxy.url — replace only the shipped default `https://localhost`
# (without a port). Anything else is treated as an operator override.
current_url="$(awk '/^[[:space:]]+url:/ { sub(/^[[:space:]]+url:[[:space:]]*/, ""); gsub(/"/, ""); print; exit }' "$TELEMETRY_CONFIG")"
if [[ "$current_url" == "https://localhost" || -z "$current_url" ]]; then
    sed -i.bak -E "s|^([[:space:]]+)url:.*|\1url: \"$CMON_PROXY_URL\"|" "$TELEMETRY_CONFIG" && rm -f "$TELEMETRY_CONFIG.bak"
    log "  set billing.cmon_proxy.url: $CMON_PROXY_URL"
else
    log "  preserving existing billing.cmon_proxy.url ($current_url)"
fi

# billing.cmon_proxy.insecure — flip false → true (cmon-proxy uses self-signed)
if grep -qE '^[[:space:]]+insecure:[[:space:]]*false' "$TELEMETRY_CONFIG"; then
    sed -i.bak -E 's|^([[:space:]]+)insecure:[[:space:]]*false.*|\1insecure: true|' "$TELEMETRY_CONFIG" && rm -f "$TELEMETRY_CONFIG.bak"
    log "  set billing.cmon_proxy.insecure: true"
else
    log "  preserving existing billing.cmon_proxy.insecure (already true or hand-edited)"
fi

# Token left empty in cmon-telemetry config — the binary's ResolveToken
# falls back to /usr/share/ccmgr/service-tokens/$NAME by default, which is
# where the bootstrap step just wrote it.

# Ownership: match the existing setup-billing convention. severalnines group
# is created by the package; falling back to root:root keeps re-runs working
# on hosts where the package layout differs.
if getent group severalnines >/dev/null 2>&1; then
    chown root:severalnines "$TELEMETRY_CONFIG"
else
    warn "  group 'severalnines' not found — leaving $TELEMETRY_CONFIG ownership unchanged"
fi
chmod 640 "$TELEMETRY_CONFIG"

# ---------- step 3: cmon-proxy ccmgr.yaml edits -----------------------------
log "applying cmon-proxy config changes via ccmgradm init --set"

# init without --local-cmon just applies --set params and saves. The CLI
# prints "Please restart 'cmon-proxy' service to apply changes"; we handle
# that ourselves in the next step.
set_args=(
    --set "billing_enabled=true"
    --set "cmon_telemetry_url=$CMON_TELEMETRY_REST"
    --set "cmon_telemetry_insecure=false"
)
if [[ $GENERATE_API_TOKEN -eq 1 && -n $API_TOKEN ]]; then
    set_args+=(--set "cmon_telemetry_token=$API_TOKEN")
fi

ccmgradm init "${set_args[@]}"

# ---------- step 4: reload cmon-proxy + restart cmon-telemetry -------------
log "reloading cmon-proxy"
reload_code="$(curl -sk -o /dev/null -w '%{http_code}' "$CMON_PROXY_URL/proxy/admin/reload" || echo 000)"
if [[ "$reload_code" != "200" ]]; then
    warn "  POST /proxy/admin/reload returned $reload_code — falling back to systemctl restart"
    systemctl restart cmon-proxy
else
    ok "  /proxy/admin/reload → 200"
fi

log "restarting cmon-telemetry (config is read once at startup; no live-reload endpoint)"
systemctl restart cmon-telemetry
systemctl enable --quiet cmon-telemetry || true

# Wait for the REST API to come up.
for _ in $(seq 1 15); do
    if curl -fsS "$CMON_TELEMETRY_REST/billing/status" >/dev/null 2>&1; then
        break
    fi
    sleep 1
done
if ! curl -fsS "$CMON_TELEMETRY_REST/billing/status" >/dev/null 2>&1; then
    warn "  cmon-telemetry didn't respond to /billing/status within 15s — check 'journalctl -u cmon-telemetry'"
fi

# ---------- step 5: verification --------------------------------------------
log "verifying"

# 5a — cmon-telemetry status.
status_json="$(curl -fsS "$CMON_TELEMETRY_REST/billing/status" 2>/dev/null || true)"
if [[ -z "$status_json" ]]; then
    warn "  /billing/status unreachable (see above)"
else
    collector_running="$(printf '%s' "$status_json" | sed -n 's/.*"collector_running":[[:space:]]*\(true\|false\).*/\1/p' | head -1)"
    if [[ "$collector_running" == "true" ]]; then
        ok "  /billing/status: collector_running=true"
    else
        warn "  /billing/status returned but collector_running is '$collector_running'"
    fi
    ed25519_fp="$(printf '%s' "$status_json" | sed -n 's/.*"ed25519_fingerprint":"\([^"]*\)".*/\1/p')"
    [[ -n "$ed25519_fp" ]] && log "  ed25519 fingerprint: $ed25519_fp"
fi

# 5b — cmon-proxy BILLING_ENABLED flag.
if curl -sk "$CMON_PROXY_URL/ccmgr.js" 2>/dev/null | grep -q '"BILLING_ENABLED":true'; then
    ok "  /ccmgr.js: BILLING_ENABLED=true"
else
    warn "  /ccmgr.js did not surface BILLING_ENABLED=true — verify cmon-proxy reloaded the config"
fi

# 5c — service-token round-trip against cmon-proxy.
controllers_count="$(
    curl -fsS -k -X POST \
        -H "Authorization: Bearer $TOKEN" \
        -H 'Content-Type: application/json' \
        "$CMON_PROXY_URL/proxy/controllers/status" \
        -d '{}' 2>/dev/null \
    | sed -n 's/.*"controllers":\[\(.*\)\]}/\1/p' \
    | grep -oE '"status":"[^"]*"' \
    | wc -l \
    | tr -d ' '
)"
if [[ "$controllers_count" =~ ^[0-9]+$ && "$controllers_count" -gt 0 ]]; then
    ok "  service token reaches $controllers_count controller(s) via cmon-proxy"
else
    warn "  service token round-trip returned no controllers — bootstrap may not have wired the token yet, or cmon-proxy needs a moment"
fi

# ---------- step 6: summary --------------------------------------------------
signing_fp="$(yaml_top_value signing_key "$TELEMETRY_CONFIG" | sha256sum | cut -c1-12)"

cat <<EOF

---------------------------------------------------------------------
Billing setup complete.

Config:
  cmon-telemetry           $TELEMETRY_CONFIG
  cmon-proxy               $CCMGR_YAML

Credentials:
  Service token hint file  $TOKEN_DIR/$NAME
  Service user keyfile     $KEY_DIR/$NAME.key
  HMAC signing key fp      sha256:$signing_fp (first 12 hex chars)
$(if [[ $GENERATE_API_TOKEN -eq 1 ]]; then
    echo "  cmon-telemetry api_token written to both \$TELEMETRY_CONFIG and \$CCMGR_YAML (\`cmon_telemetry_token\`)"
fi)

Next steps:
  - First snapshot lands within billing.interval (default 60m).
    Watch live with:  journalctl -u cmon-telemetry -f | grep tick
  - Log in to the UI at $CMON_PROXY_URL/ and open the Billing page.
  - To rotate the service token, re-run this script (or
    \`ccmgradm serviceauth-bootstrap --name $NAME --admin-user $ADMIN_USER\`).
  - To rotate the HMAC signing key, edit \`signing_key:\` in
    \$TELEMETRY_CONFIG and add the old value under \`verification_keys:\`
    so prior reports still verify.

Troubleshooting common issues (billable threshold not met, billing nav
missing, stale config after package upgrade) is covered in
TROUBLESHOOTING.md.
---------------------------------------------------------------------
EOF
