#!/bin/bash

# Setup script for SSL Certificate Renewal Cron Job
# This script installs the SSL renewal cron job in the system crontab

set -e

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to check if running as root
check_root() {
    if [ "$EUID" -ne 0 ]; then
        print_error "This script must be run as root"
        exit 1
    fi
}

# Function to install SSL renewal cron job
install_cron_job() {
    print_status "Installing SSL renewal cron job..."
    
    # Define cron job entry
    local cron_entry="0 2 * * * /root/whp/scripts/ssl-renewal-cron.sh >> /var/log/ssl-renewal.log 2>&1"
    local cron_comment="# WHP SSL Certificate Renewal - Daily at 2 AM"
    
    # Check if cron job already exists
    if crontab -l 2>/dev/null | grep -q "ssl-renewal-cron.sh"; then
        print_warning "SSL renewal cron job already exists"
        
        # Ask user if they want to update it
        read -p "Do you want to update the existing cron job? (y/n): " -n 1 -r
        echo
        
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_status "Skipping cron job installation"
            return 0
        fi
        
        # Remove existing cron job
        crontab -l 2>/dev/null | grep -v "ssl-renewal-cron.sh" | crontab -
        print_status "Removed existing cron job"
    fi
    
    # Add new cron job
    (crontab -l 2>/dev/null || echo ""; echo "$cron_comment"; echo "$cron_entry") | crontab -
    
    print_success "SSL renewal cron job installed successfully"
    print_status "Cron job will run daily at 2:00 AM"
}

# Function to create log directory
create_log_directory() {
    print_status "Creating log directory..."
    
    # Create log directory if it doesn't exist
    if [ ! -d "/var/log" ]; then
        mkdir -p /var/log
    fi
    
    # Create SSL renewal log file
    touch /var/log/ssl-renewal.log
    chmod 640 /var/log/ssl-renewal.log
    
    print_success "Log directory and file created"
}

# Function to test cron job
test_cron_job() {
    print_status "Testing SSL renewal cron job..."
    
    # Test the script in test mode
    if [ -f "/root/whp/scripts/ssl-renewal-cron.sh" ]; then
        print_status "Running test mode..."
        /root/whp/scripts/ssl-renewal-cron.sh --test
        
        print_success "Test completed successfully"
    else
        print_error "SSL renewal script not found at /root/whp/scripts/ssl-renewal-cron.sh"
        exit 1
    fi
}

# Function to setup logrotate for SSL renewal logs
setup_logrotate() {
    print_status "Setting up log rotation for SSL renewal logs..."
    
    # Create logrotate configuration
    cat > /etc/logrotate.d/ssl-renewal << 'EOF'
/var/log/ssl-renewal.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0640 root root
    postrotate
        # Nothing to do here - the log is recreated automatically
    endscript
}
EOF

    print_success "Logrotate configuration created"
}

# Function to display cron job information
display_cron_info() {
    print_status "SSL Renewal Cron Job Information:"
    echo
    print_status "Script Location: /root/whp/scripts/ssl-renewal-cron.sh"
    print_status "Log File: /var/log/ssl-renewal.log"
    print_status "Schedule: Daily at 2:00 AM"
    print_status "Logrotate: /etc/logrotate.d/ssl-renewal"
    echo
    print_status "Current cron jobs:"
    crontab -l 2>/dev/null | grep -E "(ssl-renewal|#.*SSL)" || echo "No SSL renewal cron jobs found"
    echo
    print_status "Manual Commands:"
    echo "  Test renewal:     /root/whp/scripts/ssl-renewal-cron.sh --test"
    echo "  Run renewal:      /root/whp/scripts/ssl-renewal-cron.sh"
    echo "  View logs:        tail -f /var/log/ssl-renewal.log"
    echo "  Edit cron:        crontab -e"
    echo
}

# Function to uninstall cron job
uninstall_cron_job() {
    print_status "Uninstalling SSL renewal cron job..."
    
    # Remove cron job
    crontab -l 2>/dev/null | grep -v "ssl-renewal-cron.sh" | grep -v "# WHP SSL Certificate Renewal" | crontab -
    
    # Remove logrotate configuration
    rm -f /etc/logrotate.d/ssl-renewal
    
    print_success "SSL renewal cron job uninstalled"
}

# Function to show help
show_help() {
    echo "SSL Certificate Renewal Cron Job Setup"
    echo
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  --install     Install the SSL renewal cron job (default)"
    echo "  --uninstall   Remove the SSL renewal cron job"
    echo "  --test        Test the SSL renewal script"
    echo "  --info        Display cron job information"
    echo "  --help        Show this help message"
    echo
    echo "Examples:"
    echo "  $0                # Install cron job"
    echo "  $0 --install      # Install cron job"
    echo "  $0 --test         # Test the renewal script"
    echo "  $0 --info         # Show cron job info"
    echo "  $0 --uninstall    # Remove cron job"
    echo
}

# Main function
main() {
    print_status "SSL Certificate Renewal Cron Job Setup"
    print_status "========================================"
    
    # Check if running as root
    check_root
    
    # Create log directory
    create_log_directory
    
    # Install cron job
    install_cron_job
    
    # Setup logrotate
    setup_logrotate
    
    # Test cron job
    test_cron_job
    
    # Display information
    display_cron_info
    
    print_success "SSL renewal cron job setup completed successfully"
}

# Handle command line arguments
case "${1:-install}" in
    "--install"|"install")
        main
        ;;
    "--uninstall"|"uninstall")
        check_root
        uninstall_cron_job
        ;;
    "--test"|"test")
        check_root
        test_cron_job
        ;;
    "--info"|"info")
        display_cron_info
        ;;
    "--help"|"help")
        show_help
        ;;
    *)
        print_error "Unknown option: $1"
        show_help
        exit 1
        ;;
esac 