#!/bin/bash
# mesh_report.sh — Hardened mesh tool reporter
# Usage: mesh_report.sh <tool_name> <exit_code> <duration_ms> [stdout_snippet]
set -euo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'

readonly NODE_ID="${NODE_ID:-669427}"
readonly API_BASE="${API_BASE:-https://10.69.69.1:8443}"
readonly API_URL="${API_BASE}/api/mesh"
readonly VAULT_KEY="${VAULT_KEY:-$(cat /dev/shm/vault.key 2>/dev/null || printf '%s' '')}"

# ── Input validation ───────────────────────────────────────────────────────
tool_name="${1:-unknown}"
exit_code="${2:-0}"
duration_ms="${3:-0}"
stdout_enc="${4:-}"

# Sanitize inputs
if [[ ! "${tool_name}" =~ ^[a-zA-Z0-9_-]+$ ]]; then
    printf 'ERR: invalid tool_name\n' >&2
    exit 1
fi

# Validate numeric inputs
[[ "${exit_code}" =~ ^[0-9]+$ ]] || exit_code=0
[[ "${duration_ms}" =~ ^[0-9]+$ ]] || duration_ms=0

# Truncate stdout
stdout_enc="${stdout_enc:0:512}"

if [[ -z "${VAULT_KEY}" ]]; then
    printf 'ERR: no vault key available\n' >&2
    exit 1
fi

# ── Build request ──────────────────────────────────────────────────────────
ts="$(date +%s)"
started="$(date -u +"%Y-%m-%d %H:%M:%S")"
body="$(jq -n \
    --arg nid "${NODE_ID}" \
    --arg tool "${tool_name}" \
    --argjson ec "${exit_code}" \
    --argjson dur "${duration_ms}" \
    --arg started "${started}" \
    --arg cmd "${tool_name} run" \
    '{node_id:$nid,tool_name:$tool,exit_code:$ec,duration_ms:$dur,started_at:$started,finished_at:$started,command:$cmd}')"

# Derive HMAC from vault key — NO hardcoded keys
sig="$(printf '%s:%s' "${ts}" "${body}" | openssl dgst -sha256 -hmac "${VAULT_KEY}" | awk '{print $NF}')"

# ── Send report ────────────────────────────────────────────────────────────
curl -sS --connect-timeout 5 --max-time 10 \
    -X POST "${API_URL}?action=report-tool-run" \
    -H "Content-Type: application/json" \
    -H "X-Mesh-Sig: ${sig}" \
    -H "X-Mesh-Ts: ${ts}" \
    -d "${body}" \
    2>/dev/null || true
