#!/bin/bash

# Exit on error
set -e

# Variables
ZABBIX_SERVER="zabbix-customer.au.ds.network"
ZABBIX_VERSION="6.0"

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

# Function to print colored output
print_message() {
    local color="$1"
    local message="$2"
    echo -e "${color}${message}${NC}"
}

# Function to get server IP
get_server_ip() {
    # Try to get public IP
    PUBLIC_IP=$(curl -s https://api.ipify.org 2>/dev/null || true)
    
    # If curl fails, try to get IP from network interfaces
    if [[ -z "$PUBLIC_IP" ]] || [[ "$PUBLIC_IP" == "" ]]; then
        # Get first non-local IPv4 address
        PUBLIC_IP=$(ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1' | head -1)
    fi
    
    echo "$PUBLIC_IP"
}

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    print_message "$RED" "Error: This script must be run as root"
    exit 1
fi

# Function to get hostname with cPanel support
get_hostname() {
    # Try to get cPanel hostname first
    if [[ -f /etc/wwwacct.conf ]]; then
        CPANEL_HOSTNAME=$(grep '^HOST=' /etc/wwwacct.conf | cut -d= -f2 | head -1 | xargs)
        if [[ -n "$CPANEL_HOSTNAME" && "$CPANEL_HOSTNAME" != "localhost" ]]; then
            echo "$CPANEL_HOSTNAME"
            return
        fi
    fi
    
    # Fall back to system hostname
    hostname -f 2>/dev/null || hostname
}

# Display information and ask for confirmation
show_info_and_confirm() {
    clear
    echo "================================================"
    echo "Zabbix Agent 2 Installation Script"
    echo "================================================"
    echo ""
    
    # Get system information
    HOSTNAME=$(get_hostname)
    SERVER_IP=$(get_server_ip)
    OS_NAME=$(grep '^PRETTY_NAME=' /etc/os-release | cut -d= -f2 | tr -d '"')
    
    echo "System Information:"
    echo "-------------------"
    echo "Hostname: $HOSTNAME"
    echo "Server IP: $SERVER_IP"
    echo "OS: $OS_NAME"
    echo "Zabbix Server: $ZABBIX_SERVER"
    echo "Zabbix Version: $ZABBIX_VERSION"
    echo ""
    
    # Check for AlmaLinux 9
    if ! grep -qi "almalinux.*9" /etc/os-release; then
        print_message "$RED" "Warning: This script is designed for AlmaLinux 9"
        echo "You are running: $OS_NAME"
        echo ""
    fi
    
    # Check for cPanel
    if [[ -d "/usr/local/cpanel" ]]; then
        echo "✓ cPanel detected"
    else
        echo "✗ cPanel not detected (will use system hostname)"
    fi
    echo ""
    
    # Ask for confirmation
    while true; do
        read -p "Do you want to continue with installation? (yes/no): " confirm
        case $confirm in
            [Yy][Ee][Ss]|[Yy])
                echo ""
                print_message "$YELLOW" "Starting installation..."
                return 0
                ;;
            [Nn][Oo]|[Nn])
                echo ""
                print_message "$YELLOW" "Installation cancelled by user."
                exit 0
                ;;
            *)
                echo "Please answer yes or no."
                ;;
        esac
    done
}

# Install Zabbix Agent 2
install_zabbix_agent() {
    print_message "$YELLOW" "Step 1: Adding Zabbix repository..."
    
    # Repository URL for AlmaLinux 9
    REPO_URL="https://repo.zabbix.com/zabbix/${ZABBIX_VERSION}/rhel/9/x86_64/zabbix-release-${ZABBIX_VERSION}-1.el9.noarch.rpm"
    
    # Check if repo already exists
    if rpm -qa | grep -q zabbix-release; then
        print_message "$GREEN" "✓ Zabbix repository already configured"
    else
        rpm -Uvh "$REPO_URL" --quiet
        dnf clean all > /dev/null
        print_message "$GREEN" "✓ Zabbix repository added"
    fi
    
    print_message "$YELLOW" "Step 2: Installing Zabbix Agent 2..."
    
    # Install zabbix-agent2
    dnf install -y zabbix-agent2 > /dev/null 2>&1
    
    if [[ $? -eq 0 ]]; then
        print_message "$GREEN" "✓ Zabbix Agent 2 installed successfully"
    else
        print_message "$RED" "✗ Failed to install Zabbix Agent 2"
        exit 1
    fi
}

# Configure Zabbix Agent 2
configure_zabbix_agent() {
    print_message "$YELLOW" "Step 3: Configuring Zabbix Agent 2..."
    
    CONFIG_FILE="/etc/zabbix/zabbix_agent2.conf"
    
    # Backup existing config
    if [[ -f "$CONFIG_FILE" ]]; then
        BACKUP_FILE="${CONFIG_FILE}.backup.$(date +%Y%m%d%H%M%S)"
        cp "$CONFIG_FILE" "$BACKUP_FILE"
        print_message "$GREEN" "✓ Configuration backed up to: $BACKUP_FILE"
    fi
    
    # Get hostname
    HOSTNAME=$(get_hostname)
    
    # Update configuration
    # Remove existing Server, ServerActive, and Hostname entries
    grep -v -E "^(Server|ServerActive|Hostname)=" "$CONFIG_FILE" > /tmp/zabbix_temp.conf 2>/dev/null || true
    
    # Add new configuration
    {
        echo "Server=$ZABBIX_SERVER"
        echo "ServerActive=$ZABBIX_SERVER"
        echo "Hostname=$HOSTNAME"
    } >> /tmp/zabbix_temp.conf
    
    # Replace original file
    mv /tmp/zabbix_temp.conf "$CONFIG_FILE"
    
    # Set proper permissions
    chown zabbix:zabbix "$CONFIG_FILE" 2>/dev/null || true
    chmod 644 "$CONFIG_FILE"
    
    print_message "$GREEN" "✓ Configuration updated"
    print_message "$GREEN" "  Server: $ZABBIX_SERVER"
    print_message "$GREEN" "  Hostname: $HOSTNAME"
}

# Setup cPanel monitoring (if cPanel exists)
setup_cpanel_monitoring() {
    if [[ -d "/usr/local/cpanel" ]]; then
        print_message "$YELLOW" "Step 4: Setting up cPanel monitoring..."
        
        # Create plugins directory if it doesn't exist
        PLUGIN_DIR="/etc/zabbix/zabbix_agent2.d/plugins.d"
        mkdir -p "$PLUGIN_DIR"
        
        # Create cPanel monitoring config
        CPANEL_CONF="$PLUGIN_DIR/cpanel.conf"
        cat > "$CPANEL_CONF" << 'EOF'
# cPanel monitoring for Zabbix Agent 2
UserParameter=cpanel.version,/usr/local/cpanel/cpanel -V 2>/dev/null || echo "unknown"
UserParameter=cpanel.accounts.count,ls /var/cpanel/users 2>/dev/null | wc -l
UserParameter=cpanel.domains.count,cat /etc/userdomains 2>/dev/null | wc -l
EOF
        
        chmod 644 "$CPANEL_CONF"
        chown zabbix:zabbix "$CPANEL_CONF"
        
        print_message "$GREEN" "✓ cPanel monitoring configured"
    fi
}

# Start and enable the service
start_service() {
    print_message "$YELLOW" "Step 5: Starting Zabbix Agent 2 service..."
    
    SERVICE_NAME="zabbix-agent2"
    
    # Enable and start service
    systemctl enable --now "$SERVICE_NAME" > /dev/null 2>&1
    
    # Check if service is running
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        print_message "$GREEN" "✓ Zabbix Agent 2 service is running"
    else
        print_message "$RED" "✗ Failed to start Zabbix Agent 2 service"
        echo "Trying to start manually..."
        systemctl start "$SERVICE_NAME"
        
        if systemctl is-active --quiet "$SERVICE_NAME"; then
            print_message "$GREEN" "✓ Service started successfully"
        else
            print_message "$RED" "✗ Service still not running. Check logs with: journalctl -u zabbix-agent2"
            exit 1
        fi
    fi
}

# Configure firewall for cPanel/CSF
configure_firewall() {
    if [[ -d "/usr/local/cpanel" ]] && command -v csf > /dev/null 2>&1; then
        print_message "$YELLOW" "Step 6: Configuring cPanel/CSF firewall..."
        
        # Add Zabbix server IP to CSF allow list
        ZABBIX_IP=$(dig +short "$ZABBIX_SERVER" 2>/dev/null | head -1)
        
        if [[ -n "$ZABBIX_IP" ]]; then
            # Check if already in allow list
            if ! csf -g "$ZABBIX_IP" 2>/dev/null | grep -q "already"; then
                csf -a "$ZABBIX_IP" "Zabbix Monitoring Server" > /dev/null 2>&1
                if [[ $? -eq 0 ]]; then
                    print_message "$GREEN" "✓ Added $ZABBIX_IP to CSF allow list"
                else
                    print_message "$YELLOW" "⚠ Could not add $ZABBIX_IP to CSF allow list"
                    print_message "$YELLOW" "  You may need to add it manually in WHM"
                fi
            else
                print_message "$GREEN" "✓ $ZABBIX_IP already in CSF allow list"
            fi
        else
            print_message "$YELLOW" "⚠ Could not resolve Zabbix server IP"
            print_message "$YELLOW" "  Please ensure $ZABBIX_SERVER is accessible from this server"
        fi
        
        # Restart CSF to apply changes
        csf -r > /dev/null 2>&1
    fi
}

# Show final status
show_final_status() {
    echo ""
    echo "================================================"
    print_message "$GREEN" "INSTALLATION COMPLETE"
    echo "================================================"
    echo ""
    
    HOSTNAME=$(get_hostname)
    SERVER_IP=$(get_server_ip)
    SERVICE_NAME="zabbix-agent2"
    
    echo "Installation Summary:"
    echo "---------------------"
    echo "• Zabbix Agent 2 installed successfully"
    echo "• Configuration updated"
    echo "• Service is running"
    echo ""
    echo "Server Details:"
    echo "---------------"
    echo "• Agent Hostname: $HOSTNAME"
    echo "• Server IP: $SERVER_IP"
    echo "• Zabbix Server: $ZABBIX_SERVER"
    echo "• Service Status: $(systemctl is-active $SERVICE_NAME)"
    echo "• Config File: /etc/zabbix/zabbix_agent2.conf"
    
    if [[ -d "/usr/local/cpanel" ]]; then
        echo "• cPanel Monitoring: Enabled"
    fi
    
    echo ""
    echo "Useful Commands:"
    echo "----------------"
    echo "Check service logs:   journalctl -u zabbix-agent2"
    echo "Restart service:      systemctl restart zabbix-agent2"
    echo "Check service status: systemctl status zabbix-agent2"
    echo "Test agent locally:   zabbix_agent2 -t agent.ping"
    echo ""
}

# Show Zabbix Monitoring Setup Instructions
show_zabbix_monitoring_setup() {
    HOSTNAME=$(get_hostname)
    SERVER_IP=$(get_server_ip)
    
    echo "================================================"
    print_message "$GREEN" "ZABBIX MONITORING SETUP INSTRUCTIONS"
    echo "================================================"
    echo ""
    print_message "$YELLOW" "To add this server to Zabbix monitoring, follow these steps:"
    echo ""
    
    echo "STEP-BY-STEP GUIDE:"
    echo "-------------------"
    echo ""
    echo "1. Login to Zabbix web interface"
    echo "2. Go to: Configuration → Hosts"
    echo "3. Click on 'Create host' button"
    echo ""
    echo "4. In the 'Host' tab:"
    echo "   • Host name: $HOSTNAME"
    echo "   • Templates: Search and select 'cPanel_Managed_servers'"
    echo "   • Host groups: Search and select 'cPanel_managed_servers'"
    echo ""
    echo "5. In the 'Interfaces' section:"
    echo "   • Click 'Add'"
    echo "   • Type: Agent"
    echo "   • IP address: $SERVER_IP"
    echo "   • DNS name: $HOSTNAME"
    echo "   • Port: 10050"
    echo ""
    echo "6. Click on the 'Add' button at the bottom"
    echo ""
    
    echo "REQUIRED INFORMATION FOR SETUP:"
    echo "------------------------------"
    echo "• Agent Hostname: $HOSTNAME"
    echo "• Server IP: $SERVER_IP"
    echo "• DNS Name: $HOSTNAME"
    echo "• Port: 10050"
    echo "• Template: cPanel_managed_servers"
    echo "• Host Group: cPanel_managed_servers"
    echo ""
    
    echo "VERIFICATION:"
    echo "-------------"
    echo "After adding the host in Zabbix:"
    echo "1. Wait 1-2 minutes for the first data collection"
    echo "2. Check if the host shows 'Availability' as green"
    echo "3. Verify data is being received under 'Latest data'"
    echo ""
    
    echo "TROUBLESHOOTING:"
    echo "----------------"
    echo "If the host doesn't show as available:"
    echo "1. Check firewall rules on this server:"
    echo "   firewall-cmd --list-all"
    echo "2. Verify Zabbix Agent is running:"
    echo "   systemctl status zabbix-agent2"
    echo "3. Test connectivity to Zabbix server:"
    echo "   telnet $ZABBIX_SERVER 10051"
    echo ""
    echo "================================================"
}

# Main execution
main() {
    # Show info and ask for confirmation
    show_info_and_confirm
    
    # Execute installation steps
    install_zabbix_agent
    configure_zabbix_agent
    setup_cpanel_monitoring
    start_service
    configure_firewall
    show_final_status
    show_zabbix_monitoring_setup
}

# Run main function
main
