#!/bin/bash
# =============================================================================
# data-restore.sh -- Restore Manager
# =============================================================================
# Category: data | Bird: raven | Tier: 2 | Node-aware: yes
# =============================================================================

TOOL_NAME="data-restore"
TOOL_VERSION="2.0.0"
TOOL_TIER=2
TOOL_BIRD="raven"
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}"
BACKUP_DIR="${BACKUP_DIR:-/opt/binary/backups}"

_do_send_impl() {
    local archive="${1:-}"
    if [ -z "$archive" ]; then
        echo "Usage: ${TOOL_NAME} --send <archive.tar.gz>"
        echo "Available:"
        ls -lhrt "${BACKUP_DIR}"/*.tar.gz 2>/dev/null | awk '{print "  " $NF " (" $5 ")"}'
        return 1
    fi
    [ ! -f "$archive" ] && [ -f "${BACKUP_DIR}/${archive}" ] && archive="${BACKUP_DIR}/${archive}"
    [ ! -f "$archive" ] && { echo "Archive not found: ${archive}"; return 1; }

    echo "=== Restore: ${NODE_ID} ==="
    echo "  Archive: ${archive}"
    echo "  Extracting to /tmp/restore..."
    mkdir -p /tmp/restore
    tar xzf "$archive" -C /tmp/restore 2>/dev/null
    echo "  Extracted. Review contents before applying:"
    ls -la /tmp/restore/
    echo ""
    echo "  [NOTE] Manual review required. Copy files from /tmp/restore/ to target."
    tool_audit "send" "archive=${archive} node=${NODE_ID}"
}

_do_status_impl() {
    local count=0
    [ -d "$BACKUP_DIR" ] && count=$(find "$BACKUP_DIR" -name "*.tar.gz" 2>/dev/null | wc -l)
    echo "{\"tool\":\"${TOOL_NAME}\",\"node\":\"${NODE_ID}\",\"status\":\"healthy\",\"available_backups\":${count},\"checked_at\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
}

_do_digest_impl() {
    echo "=== Restore Report: ${NODE_ID} ==="
    echo "  Backup dir: ${BACKUP_DIR}"
    ls -lhrt "${BACKUP_DIR}"/*.tar.gz 2>/dev/null | awk '{print "  " $NF " (" $5 ")"}'
}

_do_flush_impl() {
    rm -rf /tmp/restore 2>/dev/null && echo "  [CHANGED] Cleaned /tmp/restore"
    [ -f "$TOOL_LOG" ] && truncate -s 0 "$TOOL_LOG"
}

tool_help() {
    echo "${TOOL_NAME} v${TOOL_VERSION} -- Restore Manager"
    echo "  --send <archive>  Extract backup for review"
    echo "  --status          JSON pill (available backups)"
    echo "  --digest          List backups"
    echo "  --flush           Clean temp + truncate log"
}

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 "$@" ;;
    --help) tool_help ;; *) handle_standard_command "$@" ;;
esac
