#!/bin/bash

################################################################################
# Acronis Log Viewer
################################################################################
# Purpose: View and tail Acronis Cyber Protect logs
# Log location: /var/lib/Acronis/BackupAndRecovery/MMS/
# Primary log: mms.0.log
################################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$SCRIPT_DIR/lib/common-functions.sh"
source "$SCRIPT_DIR/lib/system-detect.sh"

# Require root
if [ "$EUID" -ne 0 ]; then
    print_error "This script must be run as root"
    exit 1
fi

# Log directory
LOG_DIR="/var/lib/Acronis/BackupAndRecovery/MMS"
PRIMARY_LOG="$LOG_DIR/mms.0.log"

print_banner "Acronis Logs Viewer"

# Check if Acronis is installed
if [ ! -d "$LOG_DIR" ]; then
    echo ""
    print_error "Acronis log directory not found"
    echo ""
    echo "Acronis may not be installed or logs are in a different location."
    echo ""
    press_enter
    exit 1
fi

echo ""
echo -e "${BOLD}Acronis Log Management${NC}"
echo ""
echo "Log directory: ${LOG_DIR}"
echo ""

# Show log menu
show_log_menu() {
    clear
    print_banner "Acronis Logs Viewer"
    echo ""
    echo -e "${BOLD}Available Logs:${NC}"
    echo ""

    # List all log files with sizes
    if [ -d "$LOG_DIR" ]; then
        local log_count=0
        while IFS= read -r log_file; do
            ((log_count++))
            local size=$(du -h "$log_file" 2>/dev/null | awk '{print $1}')
            local filename=$(basename "$log_file")
            local mod_time=$(stat -c %y "$log_file" 2>/dev/null | cut -d'.' -f1)
            echo -e "  ${CYAN}${log_count})${NC} ${filename}"
            echo -e "     Size: ${size} | Modified: ${mod_time}"
        done < <(find "$LOG_DIR" -name "*.log" -type f | sort)

        if [ "${log_count:-0}" -eq 0 ]; then
            echo -e "  ${DIM}No log files found${NC}"
        fi
    fi

    echo ""
    echo -e "${BOLD}Actions:${NC}"
    echo ""
    echo -e "  ${GREEN}v)${NC} View Primary Log (last 100 lines)"
    echo -e "  ${GREEN}t)${NC} Tail Primary Log (live follow)"
    echo -e "  ${GREEN}s)${NC} Search Logs"
    echo -e "  ${GREEN}e)${NC} Show Errors Only"
    echo -e "  ${GREEN}a)${NC} Archive Old Logs"
    echo ""
    echo -e "  ${RED}0)${NC} Back"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo -n "Select option: "
}

# View primary log
view_primary_log() {
    clear
    print_banner "Acronis Primary Log (Last 100 Lines)"
    echo ""

    if [ -f "$PRIMARY_LOG" ]; then
        tail -100 "$PRIMARY_LOG"
        echo ""
        echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
        echo ""
        press_enter
    else
        print_error "Primary log file not found: $PRIMARY_LOG"
        press_enter
    fi
}

# Tail primary log
tail_primary_log() {
    clear
    print_banner "Acronis Live Log (Ctrl+C to Exit)"
    echo ""
    echo "Following: $PRIMARY_LOG"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo ""

    if [ -f "$PRIMARY_LOG" ]; then
        tail -f "$PRIMARY_LOG"
    else
        print_error "Primary log file not found: $PRIMARY_LOG"
        press_enter
    fi
}

# Search logs
search_logs() {
    clear
    print_banner "Search Acronis Logs"
    echo ""
    echo -n "Enter search term: "
    read -r search_term

    if [ -z "$search_term" ]; then
        print_error "No search term provided"
        press_enter
        return
    fi

    echo ""
    echo "Searching for: ${search_term}"
    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo ""

    # Search all log files
    local found=false
    while IFS= read -r log_file; do
        if grep -qi "$search_term" "$log_file" 2>/dev/null; then
            found=true
            echo -e "${BOLD}$(basename "$log_file"):${NC}"
            grep -i --color=always "$search_term" "$log_file" | tail -20
            echo ""
        fi
    done < <(find "$LOG_DIR" -name "*.log" -type f)

    if [ "$found" = false ]; then
        echo "No matches found for: $search_term"
    fi

    echo ""
    echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
    echo ""
    press_enter
}

# Show errors only
show_errors() {
    clear
    print_banner "Acronis Errors (Last 50)"
    echo ""

    if [ -f "$PRIMARY_LOG" ]; then
        echo "Filtering for ERROR, WARN, FAIL, CRITICAL..."
        echo ""
        echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
        echo ""

        grep -iE "error|warn|fail|critical" "$PRIMARY_LOG" | tail -50 | while IFS= read -r line; do
            # Color code by severity
            if echo "$line" | grep -qi "critical"; then
                echo -e "${RED}${BOLD}${line}${NC}"
            elif echo "$line" | grep -qi "error"; then
                echo -e "${RED}${line}${NC}"
            elif echo "$line" | grep -qi "warn"; then
                echo -e "${YELLOW}${line}${NC}"
            else
                echo "$line"
            fi
        done

        echo ""
        echo -e "${CYAN}──────────────────────────────────────────────────────────────${NC}"
        echo ""
    else
        print_error "Primary log file not found"
    fi

    press_enter
}

# Archive old logs
archive_old_logs() {
    clear
    print_banner "Archive Old Logs"
    echo ""

    # Calculate total size
    local total_size=$(du -sh "$LOG_DIR" 2>/dev/null | awk '{print $1}')
    local log_count=$(find "$LOG_DIR" -name "*.log" -type f | wc -l)

    echo "Current log status:"
    echo "  Directory: $LOG_DIR"
    echo "  Total size: $total_size"
    echo "  Log files: $log_count"
    echo ""

    # Find old logs (older than 30 days)
    local old_logs=$(find "$LOG_DIR" -name "*.log" -type f -mtime +30 2>/dev/null | wc -l)

    if [ "${old_logs:-0}" -eq 0 ]; then
        echo -e "${GREEN}✓ No old logs found (>30 days)${NC}"
        echo ""
        press_enter
        return
    fi

    echo "Found $old_logs log file(s) older than 30 days"
    echo ""
    echo "Archive location: /root/acronis-logs-archive-$(date +%Y%m%d).tar.gz"
    echo ""
    echo -n "Create archive and remove old logs? (yes/no): "
    read -r confirm

    if [ "$confirm" != "yes" ]; then
        echo ""
        echo "Archive cancelled"
        press_enter
        return
    fi

    echo ""
    echo "→ Creating archive..."

    # Create archive
    local archive_name="/root/acronis-logs-archive-$(date +%Y%m%d).tar.gz"
    if find "$LOG_DIR" -name "*.log" -type f -mtime +30 -print0 2>/dev/null | tar -czf "$archive_name" --null -T -; then
        print_success "Archive created: $archive_name"

        # Remove old logs
        echo ""
        echo "→ Removing old logs..."
        find "$LOG_DIR" -name "*.log" -type f -mtime +30 -delete 2>/dev/null

        local remaining=$(find "$LOG_DIR" -name "*.log" -type f | wc -l)
        echo ""
        print_success "Old logs archived and removed"
        echo ""
        echo "Remaining log files: $remaining"
    else
        print_error "Failed to create archive"
    fi

    echo ""
    press_enter
}

# Main loop
while true; do
    show_log_menu
    read -r choice

    case $choice in
        v) view_primary_log ;;
        t) tail_primary_log ;;
        s) search_logs ;;
        e) show_errors ;;
        a) archive_old_logs ;;
        0) exit 0 ;;
        *)
            # Check if numeric selection for specific log file
            if [[ "$choice" =~ ^[0-9]+$ ]]; then
                log_files=($(find "$LOG_DIR" -name "*.log" -type f | sort))
                if [ "${choice:-0}" -gt 0 ] && [ "${choice:-0}" -le ${#log_files[@]} ]; then
                    selected_log="${log_files[$((choice-1))]}"
                    clear
                    print_banner "Log: $(basename "$selected_log")"
                    echo ""
                    tail -100 "$selected_log"
                    echo ""
                    press_enter
                else
                    print_error "Invalid log selection"
                    sleep 1
                fi
            else
                print_error "Invalid option"
                sleep 1
            fi
            ;;
    esac
done
