#!/bin/bash

# Enhanced Crontab Management Script
# This script helps install and manage the enhanced crontab entries with system logging

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
HOSTNAME=$(hostname)
ENHANCED_CRONTAB_FILE="$SCRIPT_DIR/crontab-${HOSTNAME}.txt"
BACKUP_CRONTAB_FILE="/tmp/crontab-backup-$(date +%Y%m%d_%H%M%S)"

log_message() {
    echo -e "$(date '+%H:%M:%S') $1"
}

log_error() {
    log_message "${RED}ERROR: $1${NC}"
}

log_success() {
    log_message "${GREEN}SUCCESS: $1${NC}"
}

log_warning() {
    log_message "${YELLOW}WARNING: $1${NC}"
}

log_info() {
    log_message "${BLUE}INFO: $1${NC}"
}

backup_current_crontab() {
    log_info "Creating structured backup using crontab-backup-system for host: $HOSTNAME"
    
    # Use the comprehensive backup system
    if [ -f "$SCRIPT_DIR/crontab-backup-system.sh" ]; then
        if "$SCRIPT_DIR/crontab-backup-system.sh" backup manual; then
            log_success "Structured crontab backup created successfully"
        else
            log_warning "Structured backup failed, falling back to temporary backup"
            # Fallback to simple backup
            log_info "Backing up current root crontab to $BACKUP_CRONTAB_FILE"
            if sudo crontab -l > "$BACKUP_CRONTAB_FILE" 2>/dev/null; then
                log_success "Temporary backup created successfully"
            else
                log_warning "No existing crontab found or backup failed"
            fi
        fi
    else
        log_warning "crontab-backup-system.sh not found, using temporary backup"
        # Fallback to simple backup
        log_info "Backing up current root crontab to $BACKUP_CRONTAB_FILE"
        if sudo crontab -l > "$BACKUP_CRONTAB_FILE" 2>/dev/null; then
            log_success "Temporary backup created successfully"
        else
            log_warning "No existing crontab found or backup failed"
        fi
    fi
}

install_enhanced_crontab() {
    log_info "Installing enhanced crontab entries for system: $HOSTNAME"
    
    # Check for system-specific crontab file first
    if [ ! -f "$ENHANCED_CRONTAB_FILE" ]; then
        log_warning "System-specific crontab file not found: $ENHANCED_CRONTAB_FILE"
        log_info "Available crontab files:"
        ls -la "$SCRIPT_DIR"/crontab-*.txt 2>/dev/null || log_warning "No system-specific crontab files found"
        
        log_error "No suitable crontab file found. Please create $ENHANCED_CRONTAB_FILE"
        return 1
    fi
    
    # Create a backup before making changes
    if [ -f "$SCRIPT_DIR/crontab-backup-system.sh" ]; then
        log_info "Creating pre-install backup"
        if ! "$SCRIPT_DIR/crontab-backup-system.sh" backup pre-install; then
            log_warning "Pre-install backup failed (normal for systems with no existing crontab)"
        fi
    fi
    
    # Extract just the cron entries (skip comments and empty lines)
    grep -E '^[0-9]' "$ENHANCED_CRONTAB_FILE" > /tmp/cron_entries_only.txt
    
    # Validate the crontab syntax before installing
    log_info "Validating crontab syntax"
    if [ -f "$SCRIPT_DIR/crontab-backup-system.sh" ]; then
        if ! "$SCRIPT_DIR/crontab-backup-system.sh" validate /tmp/cron_entries_only.txt; then
            log_error "Crontab syntax validation failed"
            rm -f /tmp/cron_entries_only.txt
            return 1
        fi
    else
        log_warning "Backup script not found, skipping validation"
    fi
    
    if sudo crontab /tmp/cron_entries_only.txt; then
        log_success "Enhanced crontab entries installed successfully"
        rm -f /tmp/cron_entries_only.txt
        
        # Create a post-install backup
        if [ -f "$SCRIPT_DIR/crontab-backup-system.sh" ]; then
            if ! "$SCRIPT_DIR/crontab-backup-system.sh" backup post-install; then
                log_warning "Post-install backup failed, but crontab installation was successful"
            fi
        fi
    else
        log_error "Failed to install enhanced crontab entries"
        rm -f /tmp/cron_entries_only.txt
        return 1
    fi
}

show_current_crontab() {
    log_info "Current root crontab entries:"
    echo
    sudo crontab -l 2>/dev/null || log_warning "No crontab entries found"
    echo
}

show_log_monitoring_commands() {
    log_info "Commands to monitor backup logs:"
    echo
    echo -e "${CYAN}# Use the enhanced backup log monitor:${NC}"
    echo "$SCRIPT_DIR/../backup-log-monitor.sh monitor     # Real-time monitoring"
    echo "$SCRIPT_DIR/../backup-log-monitor.sh recent 24   # Last 24 hours"
    echo "$SCRIPT_DIR/../backup-log-monitor.sh health      # System health check"
    echo "$SCRIPT_DIR/../backup-log-monitor.sh report 7    # Weekly report"
    echo
    echo -e "${CYAN}# Direct journalctl commands:${NC}"
    echo "sudo journalctl -f -t plex-backup -t backup-move -t plex-validation -t immich-backup -t plex-report"
    echo
    echo -e "${CYAN}# View logs from the last 24 hours:${NC}"
    echo "sudo journalctl --since '24 hours ago' -t plex-backup -t backup-move -t plex-validation -t immich-backup -t plex-report"
    echo
    echo -e "${CYAN}# View only error logs:${NC}"
    echo "sudo journalctl --priority=err -t plex-backup -t backup-move -t plex-validation -t immich-backup -t plex-report"
    echo
    echo -e "${CYAN}# View logs for a specific backup type (e.g., plex-backup):${NC}"
    echo "sudo journalctl -t plex-backup --since '1 week ago'"
    echo
}

setup_logrotate() {
    log_info "Setting up logrotate for backup logs"
    
    cat > /tmp/backup-logs-logrotate << 'EOF'
# Logrotate configuration for backup logs
# This ensures syslog doesn't grow too large with backup logs

/var/log/syslog {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    postrotate
        /usr/lib/rsyslog/rsyslog-rotate
    endscript
}
EOF
    
    if sudo cp /tmp/backup-logs-logrotate /etc/logrotate.d/backup-logs; then
        log_success "Logrotate configuration installed"
    else
        log_warning "Failed to install logrotate configuration"
    fi
    
    rm -f /tmp/backup-logs-logrotate
}

verify_scripts_exist() {
    log_info "Verifying all backup scripts exist and are executable"
    
    local scripts=(
        "$SCRIPT_DIR/../move-backups.sh"
        "$SCRIPT_DIR/../plex/backup-plex.sh"
        "$SCRIPT_DIR/../plex/validate-plex-backups.sh"
    )
    
    local all_good=true
    
    for script in "${scripts[@]}"; do
        if [ -f "$script" ]; then
            if [ -x "$script" ]; then
                log_success "✓ $script exists and is executable"
            else
                log_warning "! $script exists but is not executable"
                sudo chmod +x "$script"
                log_success "✓ Made $script executable"
            fi
        else
            log_error "✗ $script not found"
            all_good=false
        fi
    done
    
    if $all_good; then
        log_success "All backup scripts are ready"
    else
        log_error "Some backup scripts are missing"
        return 1
    fi
}

show_usage() {
    echo "Enhanced Crontab Management Script"
    echo
    echo "Usage: $0 [OPTION]"
    echo
    echo "Options:"
    echo "  install     Install the enhanced crontab entries with backup system"
    echo "  show        Show current crontab entries"
    echo "  backup      Backup current crontab only"
    echo "  verify      Verify all scripts exist and are executable"
    echo "  monitor     Show log monitoring commands"
    echo "  logrotate   Setup logrotate for backup logs"
    echo "  status      Show backup system health status"
    echo "  help        Show this help message"
    echo
    echo "Additional Tools:"
    echo "  $SCRIPT_DIR/crontab-backup-system.sh    Comprehensive crontab backup management"
    echo "  $SCRIPT_DIR/../backup-log-monitor.sh       Advanced backup log monitoring"
    echo
}

case "${1:-help}" in
    install)
        # Check if --help flag is present
        if [[ "$*" == *"--help"* ]]; then
            show_usage
            exit 0
        fi
        verify_scripts_exist
        backup_current_crontab
        install_enhanced_crontab
        show_current_crontab
        setup_logrotate
        show_log_monitoring_commands
        
        # Setup automated backup system
        if [ -f "$SCRIPT_DIR/crontab-backup-system.sh" ]; then
            log_info "Setting up automated crontab backup system"
            "$SCRIPT_DIR/crontab-backup-system.sh" setup-auto
        fi
        ;;
    show)
        show_current_crontab
        ;;
    backup)
        backup_current_crontab
        ;;
    verify)
        verify_scripts_exist
        ;;
    monitor)
        show_log_monitoring_commands
        ;;
    logrotate)
        setup_logrotate
        ;;
    status)
        if [ -f "$SCRIPT_DIR/../backup-log-monitor.sh" ]; then
            "$SCRIPT_DIR/../backup-log-monitor.sh" health
        else
            log_warning "Backup log monitor not found, showing basic status"
            show_current_crontab
        fi
        ;;
    help|*)
        show_usage
        ;;
esac
