#!/bin/bash
# =============================================================================
# security-response.sh -- Incident Response & Lockdown Tool
# =============================================================================
# Category:    security
# Bird:        falcon
# Tier:        1
# Node-aware:  yes
# Absorbs:     lockdown.sh, security-lockdown.sh, ceo-override.sh,
#              root_override_core.sh
#
# Standard Actions:
#   --send              Status summary of lockdown/maintenance state
#   --status            JSON pill
#   --digest            Incident response report
#   --flush             Clear lockdown state
#   --lockdown          Activate lockdown mode
#   --maintenance       Toggle maintenance mode
#   --rescue            Emergency rescue operations (break-glass)
#   --clear-queue       Clear pending veil queue (break-glass)
# =============================================================================

TOOL_NAME="security-response"
TOOL_VERSION="3.0.0"
TOOL_TIER=1
TOOL_BIRD="falcon"
TOOL_LOG="/opt/binary/logs/tools/${TOOL_NAME}.log"
TOOL_CONFIG="/etc/binary/${TOOL_NAME}.conf"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ -f "${SCRIPT_DIR}/common.sh" ]]; then source "${SCRIPT_DIR}/common.sh"
elif [[ -f "${SCRIPT_DIR}/../common.sh" ]]; then source "${SCRIPT_DIR}/../common.sh"
else echo "FATAL: common.sh not found" >&2; exit 1; fi

export BIRD_ID="${TOOL_BIRD}"

LOCKDOWN_FLAG="/etc/binary/LOCKDOWN.flag"
MAINTENANCE_FLAG="/etc/binary/MAINTENANCE.flag"

[ -f "$TOOL_CONFIG" ] && source "$TOOL_CONFIG" 2>/dev/null

CHANGES_MADE=""
_change() { CHANGES_MADE="${CHANGES_MADE}  ${1}\n"; echo "  [CHANGED] ${1}"; }

_do_send_impl() {
    echo "=== Response Status: $(ts_local) ==="
    echo "  Node: ${NODE_ID}"
    echo ""
    if [ -f "$LOCKDOWN_FLAG" ]; then
        echo "  Lockdown:    [ACTIVE]"
        cat "$LOCKDOWN_FLAG" 2>/dev/null | sed 's/^/    /'
    else
        echo "  Lockdown:    [INACTIVE]"
    fi
    if [ -f "$MAINTENANCE_FLAG" ]; then
        echo "  Maintenance: [ACTIVE]"
    else
        echo "  Maintenance: [INACTIVE]"
    fi
    echo ""
    echo "  Veil pending: $(find /opt/binary/data/pending-approvals -maxdepth 1 -name '*.json' 2>/dev/null | wc -l)"
    echo "  Strikes:      $([ -f "${STRIKE_FILE}" ] && wc -l < "${STRIKE_FILE}" || echo 0)"
    tool_audit "send" "node=${NODE_ID}"
}

_do_status_impl() {
    local lockdown="false" maintenance="false"
    [ -f "$LOCKDOWN_FLAG" ] && lockdown="true"
    [ -f "$MAINTENANCE_FLAG" ] && maintenance="true"
    local status="healthy"
    [ "$lockdown" = "true" ] && status="down"
    [ "$maintenance" = "true" ] && status="degraded"
    cat <<EOF
{"tool":"${TOOL_NAME}","node":"${NODE_ID}","status":"${status}","lockdown":${lockdown},"maintenance":${maintenance},"checked_at":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}
EOF
}

_do_digest_impl() {
    echo "=== Incident Response Report: ${NODE_ID} ==="
    _do_send_impl
    echo ""
    echo "--- Recent Audit Events ---"
    tail -20 "${AUDIT_LOG}" 2>/dev/null | while read -r line; do echo "  $line"; done
}

_do_flush_impl() {
    echo "=== Flushing ${TOOL_NAME} state ==="
    [ -f "$TOOL_LOG" ] && truncate -s 0 "$TOOL_LOG" && _change "Truncated tool log"
    echo "Flush complete on ${NODE_ID}"
}

do_lockdown() {
    local mode="${1:-activate}"
    case "$mode" in
        activate)
            require_root || return 1
            umask 077
            {
                echo "NODE=${NODE_ID}"
                echo "ACTIVATED_BY=$(whoami)"
                echo "TIMESTAMP=$(ts)"
                echo "REASON=${2:-manual}"
            } > "$LOCKDOWN_FLAG"
            chmod 600 "$LOCKDOWN_FLAG"
            tool_audit "lockdown_activate" "node=${NODE_ID} reason=${2:-manual}"
            log_ok "Lockdown ACTIVATED on ${NODE_ID}"
            ;;
        deactivate)
            require_root || return 1
            rm -f "$LOCKDOWN_FLAG"
            tool_audit "lockdown_deactivate" "node=${NODE_ID}"
            log_ok "Lockdown DEACTIVATED on ${NODE_ID}"
            ;;
        *)
            log_error "Usage: --lockdown activate|deactivate [reason]"
            return 1
            ;;
    esac
}

do_maintenance() {
    local mode="${1:-on}"
    case "$mode" in
        on)
            : > "$MAINTENANCE_FLAG"
            chmod 600 "$MAINTENANCE_FLAG" 2>/dev/null
            tool_audit "maintenance_on" "node=${NODE_ID}"
            log_ok "Maintenance mode ON"
            ;;
        off)
            rm -f "$MAINTENANCE_FLAG"
            tool_audit "maintenance_off" "node=${NODE_ID}"
            log_ok "Maintenance mode OFF"
            ;;
    esac
}

do_rescue() {
    local op="${1:-help}"
    require_root || return 1
    tool_audit "rescue" "operation=${op} node=${NODE_ID}"
    case "$op" in
        ssh)
            systemctl restart sshd 2>/dev/null
            log_ok "SSHD restarted"
            ;;
        firewall)
            firewall-cmd --reload 2>/dev/null || nft flush ruleset 2>/dev/null
            log_ok "Firewall reloaded"
            ;;
        unjail)
            rm -f /opt/binary/jail/*.jailed 2>/dev/null
            log_ok "All tools unjailed"
            ;;
        wireguard)
            systemctl restart wg-quick@wg7 2>/dev/null
            log_ok "WireGuard restarted"
            ;;
        *)
            echo "Rescue operations: ssh, firewall, unjail, wireguard"
            ;;
    esac
}

tool_help() {
    echo "${TOOL_NAME} v${TOOL_VERSION} -- Incident Response & Lockdown"
    echo ""
    echo "Actions:"
    echo "  --send                 Status summary"
    echo "  --status               JSON pill"
    echo "  --digest               Report"
    echo "  --flush                Reset"
    echo "  --lockdown act|deact   Lockdown control"
    echo "  --maintenance on|off   Maintenance mode"
    echo "  --rescue <op>          Break-glass rescue (ssh|firewall|unjail|wireguard)"
    echo "  --clear-queue          Clear veil pending queue"
}

wrap_send()   { tool_wrap "send"   _do_send_impl "$@"; }
wrap_status() { tool_wrap "status" _do_status_impl "$@"; }
wrap_digest() { tool_wrap "digest" _do_digest_impl "$@"; }
wrap_flush()  { tool_wrap "flush"  _do_flush_impl "$@"; }

tool_init
trap 'tool_complete' EXIT
case "${1:---help}" in
    --send)        shift; wrap_send "$@" ;;
    --status)      shift; wrap_status "$@" ;;
    --digest)      shift; wrap_digest "$@" ;;
    --flush)       shift; wrap_flush "$@" ;;
    --lockdown)    shift; do_lockdown "$@" ;;
    --maintenance) shift; do_maintenance "$@" ;;
    --rescue)      shift; do_rescue "$@" ;;
    --clear-queue) rm -f /opt/binary/data/pending-approvals/*.json 2>/dev/null; log_ok "Queue cleared" ;;
    --help)        tool_help ;;
    *)             handle_standard_command "$@" ;;
esac
