#!/usr/bin/env bash
# vault-kv-inner-probe.sh -- runs ON a vault-kv consumer principal as root, via
#   base64 -d | sudo bash -s <conf-path>
# AppRole login from the unit's authentic source. Secrets never printed: values read into
# vars; login response body deleted unread on 200 (it carries a client token); .errors only
# on non-200. Side effect: one real 60s-TTL Vault token per run (charm sets token_ttl=60s).
set -u   # deliberately NOT pipefail: delivered as a piped paste block (base64 -d | sudo bash -s) -- documented exemption
umask 077
CONF="${1:-}"
[ -n "$CONF" ] && [ -r "$CONF" ] || { echo "PROBE-FAIL: conf unreadable: ${CONF:-<unset>}"; exit 1; }
URL=$(grep -E '^[[:space:]]*vault_url[[:space:]]*=' "$CONF" | tail -1 | cut -d= -f2- | tr -d ' \t\r')
RID=$(grep -E '^[[:space:]]*approle_role_id[[:space:]]*=' "$CONF" | tail -1 | cut -d= -f2- | tr -d ' \t\r')
SID=$(grep -E '^[[:space:]]*approle_secret_id[[:space:]]*=' "$CONF" | tail -1 | cut -d= -f2- | tr -d ' \t\r')
echo "conf_vault_url=$URL"
[ -n "$URL" ] && [ -n "$RID" ] && [ -n "$SID" ] || { echo "PROBE-FAIL: required conf values missing"; exit 1; }
HOST=${URL#*//}; HOST=${HOST%%:*}
echo "route: $(ip -o route get "$HOST" 2>&1 | head -1)"
command -v curl >/dev/null || { echo "PROBE-FAIL: curl absent"; exit 1; }
# DOCFIX-083: credentials NEVER transit argv (visible in ps); body fed via stdin.
BODY=$(printf '{"role_id":"%s","secret_id":"%s"}' "$RID" "$SID")
RESP=/root/.vaultkv-login-resp.json
HTTP=$(printf '%s' "$BODY" | curl -s -o "$RESP" -w '%{http_code}' --max-time 10 -X POST --data @- "$URL/v1/auth/approle/login" 2>&1 || true)
echo "login_http=$HTTP"
RC=1
if [ "$HTTP" = "200" ]; then echo "PROBE-PASS"; RC=0
else echo "errors: $(python3 -c "import json;print(json.load(open('$RESP')).get('errors'))" 2>/dev/null || head -c 200 "$RESP")"; fi
rm -f "$RESP"; exit $RC
