#!/bin/bash
# =============================================================================
# admin-files.sh -- File Integrity Manager
# =============================================================================
# Category: ce | Bird: kestrel | Tier: 2 | Node-aware: yes
# Absorbs: files.sh
# Actions: --discover, --register, --audit, --quarantine, --status, --send, --digest, --flush
# =============================================================================

TOOL_NAME="admin-files"
TOOL_VERSION="3.0.0"
TOOL_TIER=2
TOOL_BIRD="kestrel"
TOOL_LOG="/opt/binary/logs/tools/${TOOL_NAME}.log"

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}"

REGISTRY_DB="${OPT_BASE}/data/file-registry.db"

_do_send_impl() {
    echo "=== File Integrity: $(ts_local) ==="
    echo "  Node: ${NODE_ID}"
    if [ -f "$REGISTRY_DB" ] && command -v sqlite3 &>/dev/null; then
        local total; total=$(sqlite3 "$REGISTRY_DB" "SELECT COUNT(*) FROM file_registry;" 2>/dev/null || echo 0)
        echo "  Registered files: ${total}"
        tool_verify_files 2>/dev/null | head -20 | sed 's/^/  /'
    else echo "  Registry not available"; fi
    tool_audit "send" "node=${NODE_ID}"
}

_do_status_impl() {
    local total=0 s="healthy"
    [ -f "$REGISTRY_DB" ] && command -v sqlite3 &>/dev/null && total=$(sqlite3 "$REGISTRY_DB" "SELECT COUNT(*) FROM file_registry;" 2>/dev/null || echo 0)
    [ "$total" -eq 0 ] && s="degraded"
    echo "{\"tool\":\"${TOOL_NAME}\",\"node\":\"${NODE_ID}\",\"status\":\"${s}\",\"registered_files\":${total},\"checked_at\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
}

_do_digest_impl() { echo "=== File Report: ${NODE_ID} ==="; _do_send_impl; }
_do_flush_impl() { [ -f "$TOOL_LOG" ] && truncate -s 0 "$TOOL_LOG"; echo "Flush complete"; }

tool_help() { echo "${TOOL_NAME} v${TOOL_VERSION} -- File Integrity"; echo "  --send|--status|--digest|--flush|--discover|--register|--audit"; }

do_send()   { tool_wrap "send"   _do_send_impl "$@"; }
do_status() { tool_wrap "status" _do_status_impl "$@"; }
do_digest() { tool_wrap "digest" _do_digest_impl "$@"; }
do_flush()  { tool_wrap "flush"  _do_flush_impl "$@"; }

tool_init; trap 'tool_complete' EXIT
case "${1:---help}" in
    --send) shift; do_send "$@" ;; --status) shift; do_status "$@" ;;
    --digest) shift; do_digest "$@" ;; --flush) shift; do_flush "$@" ;;
    --discover) find /opt/binary -type f -newer /proc 2>/dev/null | head -50 ;;
    --register) shift; tool_register_file "$@" ;;
    --audit) _do_send_impl ;; --help) tool_help ;;
    *) handle_standard_command "$@" ;;
esac
