#!/bin/bash

# ProFTPD Configuration Verification Script
# This script verifies that the ProFTPD configuration has been properly processed

# 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() {
    local status=$1
    local message=$2
    case $status in
        "OK")
            echo -e "${GREEN}✓${NC} $message"
            ;;
        "WARN")
            echo -e "${YELLOW}⚠${NC} $message"
            ;;
        "ERROR")
            echo -e "${RED}✗${NC} $message"
            ;;
        "INFO")
            echo -e "${BLUE}ℹ${NC} $message"
            ;;
    esac
}

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

# Check ProFTPD configuration file exists
check_config_file() {
    if [[ ! -f /etc/proftpd/proftpd.conf ]]; then
        print_status "ERROR" "ProFTPD configuration file not found: /etc/proftpd/proftpd.conf"
        exit 1
    fi
    print_status "OK" "ProFTPD configuration file exists"
}

# Check for unprocessed placeholders
check_placeholders() {
    local config_file="/etc/proftpd/proftpd.conf"
    local issues=0
    
    print_status "INFO" "Checking for unprocessed placeholders..."
    
    # Check for $MYSQL_PASSWORD placeholder
    if grep -q '\$MYSQL_PASSWORD' "$config_file"; then
        print_status "ERROR" "Found unprocessed \$MYSQL_PASSWORD placeholder in config"
        grep -n '\$MYSQL_PASSWORD' "$config_file"
        ((issues++))
    else
        print_status "OK" "MySQL password placeholder has been processed"
    fi
    
    # Check for $PUBLIC_IP placeholder
    if grep -q '\$PUBLIC_IP' "$config_file"; then
        print_status "ERROR" "Found unprocessed \$PUBLIC_IP placeholder in config"
        grep -n '\$PUBLIC_IP' "$config_file"
        ((issues++))
    else
        print_status "OK" "Public IP placeholder has been processed"
    fi
    
    return $issues
}

# Check MySQL connection string
check_mysql_connection() {
    local config_file="/etc/proftpd/proftpd.conf"
    
    print_status "INFO" "Checking MySQL connection configuration..."
    
    # Extract the SQLConnectInfo line
    local sql_connect_line=$(grep "SQLConnectInfo" "$config_file")
    
    if [[ -z "$sql_connect_line" ]]; then
        print_status "ERROR" "SQLConnectInfo line not found in configuration"
        return 1
    fi
    
    echo "SQLConnectInfo line:"
    echo "  $sql_connect_line"
    
    # Check if it looks reasonable (contains actual password, not placeholder)
    # Extract just the password part after 'root '
    local password_part=$(echo "$sql_connect_line" | sed 's/.*root[[:space:]]\+//')
    if [[ ${#password_part} -ge 8 && "$password_part" != "\$MYSQL_PASSWORD" ]]; then
        print_status "OK" "SQLConnectInfo appears to contain actual password"
    else
        print_status "WARN" "SQLConnectInfo may not contain valid password (length: ${#password_part})"
    fi
    
    return 0
}

# Check MasqueradeAddress
check_masquerade_address() {
    local config_file="/etc/proftpd/proftpd.conf"
    
    print_status "INFO" "Checking MasqueradeAddress configuration..."
    
    # Extract the MasqueradeAddress line
    local masquerade_line=$(grep "MasqueradeAddress" "$config_file")
    
    if [[ -z "$masquerade_line" ]]; then
        print_status "WARN" "MasqueradeAddress line not found in configuration"
        return 1
    fi
    
    echo "MasqueradeAddress line:"
    echo "  $masquerade_line"
    
    # Check if it's commented out
    if [[ "$masquerade_line" =~ ^[[:space:]]*# ]]; then
        print_status "WARN" "MasqueradeAddress is commented out - may need manual configuration"
    else
        # Check if it contains an IP address
        if [[ "$masquerade_line" =~ [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} ]]; then
            print_status "OK" "MasqueradeAddress contains valid IP address"
        else
            print_status "ERROR" "MasqueradeAddress does not contain valid IP address"
        fi
    fi
    
    return 0
}

# Test ProFTPD configuration syntax
test_config_syntax() {
    print_status "INFO" "Testing ProFTPD configuration syntax..."
    
    if proftpd -t -c /etc/proftpd/proftpd.conf >/dev/null 2>&1; then
        print_status "OK" "ProFTPD configuration syntax is valid"
    else
        print_status "ERROR" "ProFTPD configuration syntax errors found:"
        proftpd -t -c /etc/proftpd/proftpd.conf
        return 1
    fi
    
    return 0
}

# Main verification function
main() {
    echo "ProFTPD Configuration Verification Script"
    echo "========================================"
    echo
    
    check_root
    check_config_file
    
    local total_issues=0
    
    # Check for unprocessed placeholders
    check_placeholders
    ((total_issues += $?))
    
    echo
    
    # Check specific configuration sections
    check_mysql_connection
    check_masquerade_address
    
    echo
    
    # Test configuration syntax
    test_config_syntax
    ((total_issues += $?))
    
    echo
    echo "========================================"
    
    if [[ $total_issues -eq 0 ]]; then
        print_status "OK" "ProFTPD configuration verification completed successfully"
        echo
        print_status "INFO" "Next steps:"
        echo "  1. Restart ProFTPD service: systemctl restart proftpd"
        echo "  2. Check service status: systemctl status proftpd"
        echo "  3. Test FTP connection with a user account"
        echo "  4. Run FTP diagnostic script: /root/whp/scripts/ftp-diagnostic.sh"
    else
        print_status "ERROR" "ProFTPD configuration has $total_issues issue(s) that need to be resolved"
        echo
        print_status "INFO" "Common fixes:"
        echo "  1. Re-run the setup script: /root/whp/setup.sh"
        echo "  2. Check MySQL password in /root/.my.cnf"
        echo "  3. Verify server IP detection"
        echo "  4. Manual configuration may be needed"
    fi
    
    echo
}

# Run main function
main "$@" 