#!/bin/bash
# CGI script pour supprimer une clé Salt
# Usage: curl http://server:8080/cgi-bin/delete-salt-key.sh?minion_id=gw-xxx

echo "Content-Type: application/json"
echo ""

# Extraire minion_id de QUERY_STRING
MINION_ID=$(echo "$QUERY_STRING" | sed -n 's/.*minion_id=\([^&]*\).*/\1/p')

if [ -z "$MINION_ID" ]; then
    echo '{"status":"error","message":"minion_id required"}'
    exit 0
fi

# Valider le format (sécurité)
if ! echo "$MINION_ID" | grep -qE '^gw-[a-f0-9]{12}$'; then
    echo '{"status":"error","message":"invalid minion_id format"}'
    exit 0
fi

# Supprimer la clé (accepted, unaccepted, rejected, denied)
salt-key -d "$MINION_ID" -y 2>/dev/null || true
salt-key -r "$MINION_ID" -y 2>/dev/null || true
salt-key -D "$MINION_ID" -y 2>/dev/null || true

echo "{\"status\":\"ok\",\"minion_id\":\"$MINION_ID\",\"message\":\"key deleted\"}"
