#!/bin/bash
shopt -s nullglob  # Fix for basename error
# Global variables for VPS migration
source_os=""
source_disk_gb=""
source_mem_gb=""
backup_size=""
dest_os=""
dest_disk_gb=""
dest_mem_gb=""
dest_mysql_version=""
dest_php_version=""

# MySQL/MariaDB compatibility matrix
declare -A MYSQL_COMPATIBILITY=(
    ["5.1"]="5.1 5.5 5.6 5.7 8.0"
    ["5.5"]="5.5 5.6 5.7 8.0"
    ["5.6"]="5.6 5.7 8.0"
    ["5.7"]="5.7 8.0"
    ["8.0"]="8.0"

    ["10.0"]="10.0 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.1"]="10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.2"]="10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.3"]="10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.4"]="10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.5"]="10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.6"]="10.6 10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.7"]="10.7 10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.8"]="10.8 10.9 10.10 10.11 10.12 15.1"
    ["10.9"]="10.9 10.10 10.11 10.12 15.1"
    ["10.10"]="10.10 10.11 10.12 15.1"
    ["10.11"]="10.11 10.12 15.1"
    ["10.12"]="10.12 15.1"
    ["15.1"]="15.1"

    ["5.7"]+=" 10.2 10.3"
)

# Our nameserver list
OUR_NAMESERVERS=(
    "ns1.crazydomains.com"
    "ns2.crazydomains.com"
    "ns1.syrahost.com"
    "ns2.syrahost.com"
    "ns1.premium.exchange"
    "ns2.premium.exchange"
    "ns3.premium.exchange"
    "ns4.premium.exchange"
    "ns1.vodien.com"
    "ns2.vodien.com"
    "ns3.vodien.com"
)

# Function to check MySQL/MariaDB compatibility
check_mysql_compatibility() {
    local source_version="$1"
    local dest_version="$2"

    local source_base=$(echo "$source_version" | grep -oE '[0-9]+\.[0-9]+')
    local dest_base=$(echo "$dest_version" | grep -oE '[0-9]+\.[0-9]+')

    local source_type="mysql"
    [[ "$source_version" == *"MariaDB"* ]] && source_type="mariadb"
    local dest_type="mysql"
    [[ "$dest_version" == *"MariaDB"* ]] && dest_type="mariadb"

    if (( $(echo "$source_base > $dest_base" | bc -l) )); then
        echo "❌ Downgrade not supported ($source_version → $dest_version)"
        return 1
    fi

    if [[ "$source_type" == "mysql" && "$dest_type" == "mariadb" ]]; then
        if [[ "$source_base" == "5.7" && ("$dest_base" == "10.2" || "$dest_base" == "10.3") ]]; then
            echo "⚠️ Partially compatible ($source_version → $dest_version). Some features may not work correctly."
            return 0
        else
            echo "❌ Incompatible ($source_version → $dest_version). MySQL cannot be migrated to this MariaDB version."
            return 1
        fi
    fi

    if [[ "$source_type" == "mariadb" && "$dest_type" == "mysql" ]]; then
        echo "❌ Incompatible ($source_version → $dest_version). MariaDB cannot be migrated to MySQL."
        return 1
    fi

    if [[ -n "${MYSQL_COMPATIBILITY[$source_base]}" ]]; then
        if [[ "${MYSQL_COMPATIBILITY[$source_base]}" == *"$dest_base"* ]]; then
            echo "✅ Compatible ($source_version → $dest_version)"
            return 0
        fi
    fi

    echo "❌ Unknown compatibility ($source_version → $dest_version)"
    return 1
}

# Function to get MySQL version correctly
get_mysql_version() {
    local version_output=$(mysql -V 2>/dev/null)

    if [[ "$version_output" =~ "Distrib "[0-9]+\.[0-9]+\.[0-9]+ ]]; then
        mysql_version_full=$(echo "$version_output" | grep -oP "Distrib \K[0-9]+\.[0-9]+\.[0-9]+")
        mysql_version=$(echo "$mysql_version_full" | grep -oE '[0-9]+\.[0-9]+')
        echo "MySQL $mysql_version_full"
    elif [[ "$version_output" =~ "Distrib "[0-9]+\.[0-9]+\.[0-9]+-MariaDB ]]; then
        mysql_version_full=$(echo "$version_output" | grep -oP "Distrib \K[0-9]+\.[0-9]+\.[0-9]+-MariaDB")
        mysql_version=$(echo "$mysql_version_full" | grep -oE '[0-9]+\.[0-9]+')
        echo "MariaDB $mysql_version_full"
    else
        mysql_version_full=$(mysql -V | awk '{print $3}')
        mysql_version=$(echo "$mysql_version_full" | grep -oE '[0-9]+\.[0-9]+')
        echo "$mysql_version_full"
    fi
}

# Function to display menu
show_menu() {
    clear
    echo "-------------------------------------"
    echo "  Migration Type Selection Menu"
    echo "-------------------------------------"
    echo "1. Shared to Shared"
    echo "2. Shared to VPS"
    echo "3. VPS to VPS"
    echo "4. Exit"
    echo "-------------------------------------"
    read -rp "Please select migration type (1-4): " choice
}

# Function to get system information for VPS to VPS migration
get_system_info() {
    # Reset global variables
    source_os=""
    source_disk_gb=""
    source_mem_gb=""
    backup_size=""
    dest_os=""
    dest_disk_gb=""
    dest_mem_gb=""
    dest_mysql_version=""
    dest_php_version=""

    echo -e "\n=== System Information ==="
    echo "==================================================================="

    # Operating System
    echo "Operating System:"
    if [ -f /etc/os-release ]; then
        source /etc/os-release
        # Extract OS name and major version only
        os_name=$(echo "$PRETTY_NAME" | awk '{print $1}')
        major_version=$(echo "$VERSION_ID" | cut -d. -f1)
        source_os="$os_name $major_version"
        echo "$PRETTY_NAME → Normalized to: $source_os"
    elif [ -f /etc/redhat-release ]; then
        redhat_release=$(cat /etc/redhat-release)
        # Extract OS name and major version only
        os_name=$(echo "$redhat_release" | awk '{print $1}')
        if [[ "$os_name" == "CentOS" ]]; then
            major_version=$(echo "$redhat_release" | grep -oE '[0-9]+\.[0-9]+' | cut -d. -f1)
        else
            major_version=$(echo "$redhat_release" | grep -oE '[0-9]+' | head -n1)
        fi
        source_os="$os_name $major_version"
        echo "$redhat_release → Normalized to: $source_os"
    else
        source_os="Unknown OS"
        echo "Unknown OS"
    fi

    # Disk Usage
    echo -e "\nDisk Usage:"
    df -h --total | grep total | awk '{print "Total: " $2 ", Used: " $3 ", Free: " $4}'
    total_kb=$(df -k --total | grep total | awk '{print $2}')
    source_disk_gb=$(echo "scale=2; $total_kb / 1024 / 1024" | bc)

    # Memory Usage
    echo -e "\nMemory Usage:"
    free -h | grep Mem | awk '{print "Total: " $2 ", Used: " $3 ", Free: " $4}'
    total_mb=$(free -m | grep Mem | awk '{print $2}')
    source_mem_gb=$(echo "scale=2; $total_mb / 1024" | bc)

    # Backups Usage
    echo -e "\nBackups Usage:"
    if [ -d /backup ]; then
        backup_size=$(du -sh /backup | awk '{print $1}')
        echo "/backup usage: $backup_size"
    else
        backup_size="0"
        echo "/backup directory not found"
    fi

    # Databases Size
    echo -e "\nDatabases Usage (sorted by size):"
    declare -A db_sizes
    total_db_size_kb=0

    # Collect database sizes
    for db_dir in /var/lib/mysql/*/; do
        db_name=$(basename "$db_dir" 2>/dev/null || echo "loading")
        size_kb=$(du -sk "$db_dir" 2>/dev/null | awk '{print $1}')
        [ -z "$size_kb" ] && continue
        db_sizes["$db_name"]=$size_kb
        total_db_size_kb=$((total_db_size_kb + size_kb))
    done

    # Sort databases by size (descending)
    if [ ${#db_sizes[@]} -gt 0 ]; then
        while IFS= read -r line; do
            db_name=$(echo "$line" | cut -d: -f1)
            size_kb=$(echo "$line" | cut -d: -f2)
            size_mb=$(echo "scale=2; $size_kb / 1024" | bc)
            size_gb=$(echo "scale=2; $size_kb / 1048576" | bc)
            printf "%-30s %12.2f MB %8.2f GB\n" "$db_name" "$size_mb" "$size_gb"
        done < <(for db in "${!db_sizes[@]}"; do echo "$db:${db_sizes[$db]}"; done | sort -t: -k2 -nr)
        
        total_db_size_gb=$(echo "scale=2; $total_db_size_kb / 1048576" | bc)
        echo "Total databases size: $(echo "scale=2; $total_db_size_kb / 1024" | bc) MB ($total_db_size_gb GB)"
    else
        echo "No databases found"
    fi

    # MySQL Version
    echo -e "\nMySQL Version Available:"
    get_mysql_version

    # MySQL Mode
    echo -e "\nMySQL Mode:"
    mysql -e "show variables like 'sql_mode'" 2>/dev/null | grep -v "Variable_name" | awk '{print $2}'

    # PHP Versions with domain names
    echo -e "\nPHP Versions Available:"

    php_versions=()
    {
        declare -A php_map

        while IFS= read -r line; do
            domain=$(echo "$line" | cut -d':' -f1)
            phpver_raw=$(echo "$line" | awk -F'==' '{print $NF}')
            phpver=$(echo "$phpver_raw" | sed -E 's/.*php//; s/^/PHP/')

            # Group domains by cleaned PHP version
            if [[ -n "$phpver" ]]; then
                if [[ -n "${php_map[$phpver]}" ]]; then
                    php_map["$phpver"]+=",${domain}"
                else
                    php_map["$phpver"]="$domain"
                fi
            fi
        done < /etc/userdatadomains

        # Get all installed ea-php versions from /opt/cpanel/ea-php*
        for dir in /opt/cpanel/ea-php*; do
            if [[ -d "$dir" ]]; then
                version=$(basename "$dir" 2>/dev/null || echo "loading" | sed 's/ea-php//')
                key="PHP$version"
                if [[ -n "${php_map[$key]}" ]]; then
                    echo "$key: ${php_map[$key]}"
                else
                    echo "$key: No domains"
                fi
            fi
        done
    }

    # Apache Version
    echo -e "\nApache Version:"
    httpd -v 2>/dev/null | head -n1 || apache2 -v 2>/dev/null | head -n1 || echo "Apache version not found"

    # Domains Status
    echo -e "\nNumber of domains running on source server:"
    if [ -f /etc/userdatadomains ]; then
        total_domains=$(wc -l < /etc/userdatadomains)
        echo "Total domains: $total_domains"

        # Get working/not working domains
        working_count=0
        not_working_count=0
        not_working_list=()

        while IFS= read -r domain_line; do
            domain=$(echo "$domain_line" | cut -d: -f1)
            status_output=$(check_website_status "$domain")
            status=$(echo "$status_output" | awk -F ' => ' '{print $2}')

            if [[ "$status" == "Working" ]]; then
                ((working_count++))
            else
                ((not_working_count++))
                not_working_list+=("$domain: $status")
            fi
        done < <(grep -v '^#' /etc/userdatadomains)

        echo "Working: $working_count"
        echo "Not working: $not_working_count"
        if [ ${#not_working_list[@]} -gt 0 ]; then
            echo "List of domains not working:"
            for domain_status in "${not_working_list[@]}"; do
                echo "  - $domain_status"
            done
        fi
    else
        echo "No domains found in /etc/userdatadomains"
    fi

    # Domains NS Status
    echo -e "\nDomains NS Status:"
    if [ -f /etc/userdatadomains ]; then
        total_domains=$(wc -l < /etc/userdatadomains)
        echo "Total domains: $total_domains"

        ns_with_us=0
        ns_not_with_us=0
        not_with_us_list=()

        while IFS= read -r domain_line; do
            domain=$(echo "$domain_line" | cut -d: -f1)
            nameservers=$(get_nameservers "$domain")
            found=0

            for ns in $nameservers; do
                for our_ns in "${OUR_NAMESERVERS[@]}"; do
                    if [[ "$ns" == "$our_ns" ]]; then
                        found=1
                        break 2
                    fi
                done
            done

            if [ $found -eq 1 ]; then
                ((ns_with_us++))
            else
                ((ns_not_with_us++))
                not_with_us_list+=("$domain: $nameservers")
            fi
        done < <(grep -v '^#' /etc/userdatadomains)

        echo "NS with us: $ns_with_us"
        echo "Not with us: $ns_not_with_us"
        if [ ${#not_with_us_list[@]} -gt 0 ]; then
            echo "List of domains not pointing to our NS:"
            for domain_ns in "${not_with_us_list[@]}"; do
                echo "  - $domain_ns"
            done
        fi
    else
        echo "No domains found in /etc/userdatadomains"
    fi

    echo "==================================================================="

    # Get destination server information
    echo -e "\nPlease provide destination server information:"
    echo "Operating System:"
    echo "1. CentOS 7"
    echo "2. CentOS 8"
    echo "3. AlmaLinux 8"
    echo "4. AlmaLinux 9"
    echo "5. CloudLinux 7"
    echo "6. CloudLinux 8"
    read -rp "Select OS (1-6): " os_choice
    case $os_choice in
        1) dest_os="CentOS 7";;
        2) dest_os="CentOS 8";;
        3) dest_os="AlmaLinux 8";;
        4) dest_os="AlmaLinux 9";;
        5) dest_os="CloudLinux 7";;
        6) dest_os="CloudLinux 8";;
        *) dest_os="Unknown";;
    esac

    read -rp "Disk Available in GB: " dest_disk_gb
    read -rp "Memory / RAM in GB: " dest_mem_gb

    echo -e "\nMySQL Version:"
    echo "1. MySQL 5.7"
    echo "2. MySQL 8.0"
    echo "3. MariaDB 10.3"
    echo "4. MariaDB 10.4"
    echo "5. MariaDB 10.5"
    echo "6. MariaDB 10.6"
    echo "7. MariaDB 10.11"
    echo "8. MariaDB 10.12"
    echo "9. MariaDB 15.1"
    read -rp "Select MySQL version (1-9): " mysql_choice
    case $mysql_choice in
        1) dest_mysql_version="5.7"; dest_mysql_full="MySQL 5.7";;
        2) dest_mysql_version="8.0"; dest_mysql_full="MySQL 8.0";;
        3) dest_mysql_version="10.3"; dest_mysql_full="MariaDB 10.3";;
        4) dest_mysql_version="10.4"; dest_mysql_full="MariaDB 10.4";;
        5) dest_mysql_version="10.5"; dest_mysql_full="MariaDB 10.5";;
        6) dest_mysql_version="10.6"; dest_mysql_full="MariaDB 10.6";;
        7) dest_mysql_version="10.11"; dest_mysql_full="MariaDB 10.11";;
        8) dest_mysql_version="10.12"; dest_mysql_full="MariaDB 10.12";;
        9) dest_mysql_version="15.1"; dest_mysql_full="MariaDB 15.1";;
        *) dest_mysql_version="10.11"; dest_mysql_full="MariaDB 10.11";;
    esac

    echo -e "\nPHP Versions:"
    echo "1. PHP 5.6"
    echo "2. PHP 7.0"
    echo "3. PHP 7.1"
    echo "4. PHP 7.2"
    echo "5. PHP 7.3"
    echo "6. PHP 7.4"
    echo "7. PHP 8.0"
    echo "8. PHP 8.1"
    echo "9. PHP 8.2"
    echo "10. PHP 8.3"
    echo "11. PHP 8.4"
    read -rp "Select lowest PHP version available (1-11): " php_choice
    case $php_choice in
        1) dest_php_version="5.6";;
        2) dest_php_version="7.0";;
        3) dest_php_version="7.1";;
        4) dest_php_version="7.2";;
        5) dest_php_version="7.3";;
        6) dest_php_version="7.4";;
        7) dest_php_version="8.0";;
        8) dest_php_version="8.1";;
        9) dest_php_version="8.2";;
        10) dest_php_version="8.3";;
        11) dest_php_version="8.4";;
        *) dest_php_version="8.0";;
    esac
}

# Function to collect user information for VPS
collect_info_vps() {
    get_system_info
}

# Function to generate VPS migration report
generate_vps_migration_report() {
    echo -e "\n=== VPS Migration Report ==="
    echo "Source OS: $source_os"
    echo "Destination OS: $dest_os"
    echo ""
    echo "Disk Space:"
    echo "Source: ${source_disk_gb}GB"
    echo "Destination: ${dest_disk_gb}GB"
    echo ""
    echo "Memory:"
    echo "Source: ${source_mem_gb}GB"
    echo "Destination: ${dest_mem_gb}GB"
    echo ""
    echo "MySQL Version:"
    echo "Source: $(get_mysql_version)"
    echo "Destination: $dest_mysql_full"
    echo ""
    echo "PHP Version:"
    echo "Destination minimum: $dest_php_version"
    echo ""
    echo "Backup Size: $backup_size"
}

# Function to check if nameservers are Cloudflare
is_cloudflare_nameserver() {
    domain="$1"
    nameservers=$(get_nameservers "$domain")
    for ns in $nameservers; do
        if [[ "$ns" == *"cloudflare"* ]] || [[ "$ns" == *"ns.cloudflare.com"* ]]; then
            return 0
        fi
    done
    return 1
}

# Function to check website status
check_website_status() {
    domain="$1"
    if [[ -z "$domain" ]]; then
        echo "Empty domain."
        return
    fi

    if is_cloudflare_nameserver "$domain"; then
        echo "$domain => Cloudflare NS detected (manual verification needed)"
        return
    fi

    if ! dig +short "$domain" | grep -qE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'; then
        echo "$domain => Not registered or no DNS record"
        return
    fi

    result=$(curl -s -L --max-time 10 -w "HTTPSTATUS:%{http_code}" "http://$domain" -o /tmp/resp.html)
    body=$(< /tmp/resp.html)
    status_code=$(echo "$result" | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')

    if [[ "$status_code" =~ ^5 ]]; then
        status_msg="Server Error ($status_code)"
    elif [[ "$status_code" == "403" ]]; then
        status_msg="Forbidden (403)"
    elif [[ "$status_code" == "404" ]]; then
        status_msg="Not Found (404)"
    elif echo "$body" | grep -qiE "database error|error establishing a database connection|mysqli_connect"; then
        status_msg="Database Error"
    elif [[ "$status_code" =~ ^4 ]]; then
        status_msg="Client Error ($status_code)"
    elif [[ "$status_code" == "000" ]]; then
        status_msg="Connection Failed"
    else
        status_msg="Working"
    fi

    echo "$domain => $status_msg"
}

# Function to get all domains and their statuses
get_all_domains_status() {
    # Get main domain status
    main_status=$(check_website_status "$MAINDOMAIN")
    all_domains_status=("$main_status")

    # Get addon domains (excluding parked/aliases)
    addon_domains=$(grep "addon" /etc/userdatadomains | grep "^.*: $CPUSER==" | cut -d: -f1)

    # Check status for each addon domain
    for domain in $addon_domains; do
        domain_status=$(check_website_status "$domain")
        all_domains_status+=("$domain_status")
    done

    # Check domain statuses
    main_domain_working=false
    addon_domains_exist=false
    any_addon_working=false
    any_addon_not_working=false

    for status in "${all_domains_status[@]}"; do
        domain=$(echo "$status" | awk -F ' => ' '{print $1}')
        status_text=$(echo "$status" | awk -F ' => ' '{print $2}')

        if [[ "$domain" == "$MAINDOMAIN" ]]; then
            if [[ "$status_text" == "Working" ]]; then
                main_domain_working=true
            fi
        else
            addon_domains_exist=true
            if [[ "$status_text" == "Working" ]]; then
                any_addon_working=true
            else
                any_addon_not_working=true
            fi
        fi
    done

    # Format the output
    formatted_status=""
    for status in "${all_domains_status[@]}"; do
        formatted_status+="$status\n"
    done

    echo -e "$formatted_status"
    echo "MainDomainWorking:$main_domain_working"
    echo "AddonDomainsExist:$addon_domains_exist"
    echo "AnyAddonWorking:$any_addon_working"
    echo "AnyAddonNotWorking:$any_addon_not_working"
}

# Function to get DNS records
get_dns_records() {
    domain="$1"
    if [[ -z "$domain" ]]; then
        echo "No domain specified"
        return
    fi

    if is_cloudflare_nameserver "$domain"; then
        echo "Cloudflare nameservers detected - A records should be verified manually"
        return
    fi

    a_records=$(dig +short "$domain" A)
    mx_records=$(dig +short "$domain" MX | sort -n)
    txt_records=$(dig +short "$domain" TXT)
    cname_records=$(dig +short "$domain" CNAME)

    dns_info=""
    if [[ -n "$a_records" ]]; then
        dns_info+="A Records:\n$a_records\n"
    fi
    if [[ -n "$mx_records" ]]; then
        dns_info+="\nMX Records:\n$mx_records\n"
    fi
    if [[ -n "$txt_records" ]]; then
        dns_info+="\nTXT Records:\n$txt_records\n"
    fi
    if [[ -n "$cname_records" ]]; then
        dns_info+="\nCNAME Records:\n$cname_records\n"
    fi

    echo -e "$dns_info"
}

# Function to get database details
get_database_details() {
    DBS=$(grep -rh "DB_NAME" "$USER_HOME/public_html" 2>/dev/null | \
          grep -oP "['\"]\w+['\"]" | tr -d "'" | tr -d '"' | sort -u)

    db_details=()
    total_db_size_kb=0

    if [ -n "$DBS" ]; then
        for db in $DBS; do
            if [ -d "$MYSQL_DIR/$db" ]; then
                db_size_kb=$(du -sk "$MYSQL_DIR/$db" 2>/dev/null | awk '{print $1}')
                db_size_mb=$(echo "scale=2; $db_size_kb / 1024" | bc)
                total_db_size_kb=$((total_db_size_kb + db_size_kb))
                db_details+=("$db ($db_size_mb MB)")
            fi
        done
    fi

    total_db_size_mb=$(echo "scale=2; $total_db_size_kb / 1024" | bc)

    for db in "${db_details[@]}"; do
        echo "$db"
    done
    echo "$total_db_size_mb"
}

# Function to get nameservers
get_nameservers() {
    domain="$1"
    if [[ -z "$domain" ]]; then
        echo "No domain specified"
        return
    fi

    nameservers=$(host -t ns "$domain" 2>/dev/null | awk '{print $4}' | sed 's/\.$//')
    if [[ -z "$nameservers" ]]; then
        echo "No nameservers found"
    else
        echo "$nameservers"
    fi
}

# Function to normalize PHP version
normalize_php_version() {
    php_version="$1"
    normalized=$(echo "$php_version" | sed 's/^ea-//')

    if [[ "$php_version" == nf-php* ]]; then
        normalized=$(echo "$php_version" | sed 's/^nf-php//')
    fi

    if [[ "$normalized" =~ ^[0-9]{2}$ ]]; then
        normalized="${normalized:0:1}.${normalized:1:1}"
    fi

    echo "$normalized"
}

# Function to compare PHP versions
compare_php_versions() {
    version1=$(normalize_php_version "$1")
    version2=$(normalize_php_version "$2")

    if [[ "$version1" == "$version2" ]]; then
        echo "0"
    elif [[ "$(printf "%s\n%s" "$version1" "$version2" | sort -V | head -n1)" == "$version1" ]]; then
        echo "-1"
    else
        echo "1"
    fi
}

# Function to select MySQL version for VPS migrations
select_mysql_version() {
    echo ""
    echo "Available MySQL/MariaDB Versions:"
    echo "1. MySQL 5.7"
    echo "2. MySQL 8.0"
    echo "3. MariaDB 10.3"
    echo "4. MariaDB 10.4"
    echo "5. MariaDB 10.5"
    echo "6. MariaDB 10.6"
    echo "7. MariaDB 10.11"
    echo "8. MariaDB 10.12"
    echo "9. MariaDB 15.1"
    echo ""

    read -rp "Please select the destination MySQL version (1-9): " mysql_choice
    case $mysql_choice in
        1) dest_mysql_version="5.7"; dest_mysql_full="MySQL 5.7";;
        2) dest_mysql_version="8.0"; dest_mysql_full="MySQL 8.0";;
        3) dest_mysql_version="10.3"; dest_mysql_full="MariaDB 10.3";;
        4) dest_mysql_version="10.4"; dest_mysql_full="MariaDB 10.4";;
        5) dest_mysql_version="10.5"; dest_mysql_full="MariaDB 10.5";;
        6) dest_mysql_version="10.6"; dest_mysql_full="MariaDB 10.6";;
        7) dest_mysql_version="10.11"; dest_mysql_full="MariaDB 10.11";;
        8) dest_mysql_version="10.12"; dest_mysql_full="MariaDB 10.12";;
        9) dest_mysql_version="15.1"; dest_mysql_full="MariaDB 15.1";;
        *) dest_mysql_version="10.11"; dest_mysql_full="MariaDB 10.11";;
    esac

    mysql_compatibility_result=$(check_mysql_compatibility "$mysql_version_full" "$dest_mysql_full")
    if [[ "$mysql_compatibility_result" == ✅* ]]; then
        mysql_compatibility="Compatible"
        mysql_compatibility_note=""
    elif [[ "$mysql_compatibility_result" == ⚠️* ]]; then
        mysql_compatibility="Partially Compatible"
        mysql_compatibility_note="$mysql_compatibility_result"
    else
        mysql_compatibility="Not Compatible"
        mysql_compatibility_note="$mysql_compatibility_result"
    fi
}

# Function to check if this is an email-only migration
is_email_only_migration() {
    if [ -d "$USER_HOME/public_html" ] && [ "$(ls -A $USER_HOME/public_html 2>/dev/null)" ]; then
        return 1
    fi

    domains_info=$(get_all_domains_status)
    main_domain_working=$(echo -e "$domains_info" | grep "MainDomainWorking:" | cut -d: -f2)
    any_addon_working=$(echo -e "$domains_info" | grep "AnyAddonWorking:" | cut -d: -f2)

    if [[ "$main_domain_working" == "true" || "$any_addon_working" == "true" ]]; then
        return 1
    fi

    if [ -f "/var/cpanel/users/$CPUSER" ]; then
        email_count=$(uapi --user="$CPUSER" Email list_pops | grep -c "email:")
        if [ "$email_count" -gt 0 ]; then
            return 0
        fi
    fi

    return 1
}

# Function to perform prechecks
perform_prechecks() {
    echo -e "\nPerforming prechecks for $CPUSER..."

    domains_info=$(get_all_domains_status)
    all_domains_status=$(echo -e "$domains_info" | head -n -4)
    main_domain_working=$(echo -e "$domains_info" | grep "MainDomainWorking:" | cut -d: -f2)
    addon_domains_exist=$(echo -e "$domains_info" | grep "AddonDomainsExist:" | cut -d: -f2)
    any_addon_working=$(echo -e "$domains_info" | grep "AnyAddonWorking:" | cut -d: -f2)
    any_addon_not_working=$(echo -e "$domains_info" | grep "AnyAddonNotWorking:" | cut -d: -f2)

    website_size_kb=$(du -sk "$USER_HOME/public_html" 2>/dev/null | awk '{print $1}')
    [ -z "$website_size_kb" ] && website_size_kb=0

    if [ "$website_size_kb" -ge 1048576 ]; then
        website_size_gb=$(echo "scale=2; $website_size_kb / 1024 / 1024" | bc)
        website_size_mb=$(echo "scale=0; $website_size_kb / 1024" | bc)
        website_size_display="$website_size_gb GB ($website_size_mb MB)"
    else
        website_size_mb=$(echo "scale=0; $website_size_kb / 1024" | bc)
        website_size_display="$website_size_mb MB"
    fi

    email_count=0
    if [ -f "/var/cpanel/users/$CPUSER" ]; then
        email_count=$(uapi --user="$CPUSER" Email list_pops | grep -c "email:")
    fi

    total_email_size_kb=0
    big_mail_users=()

    if [ -d "$USER_HOME/mail" ]; then
        while IFS= read -r -d '' dir; do
            size_kb=$(du -sk "$dir" 2>/dev/null | awk '{print $1}')
            size_gb=$(echo "scale=2; $size_kb / 1024 / 1024" | bc)
            email=$(echo "$dir" | sed "s|$USER_HOME/mail/||" | sed 's|/|@|')

            total_email_size_kb=$((total_email_size_kb + size_kb))

            if (( $(echo "$size_gb > 10" | bc -l) )); then
                big_mail_users+=("$email ($size_gb GB)")
            fi
        done < <(find "$USER_HOME/mail" -mindepth 2 -maxdepth 2 -type d -print0)
    fi

    if [ "$total_email_size_kb" -ge 1048576 ]; then
        total_email_size_gb=$(echo "scale=2; $total_email_size_kb / 1024 / 1024" | bc)
        total_email_size_mb=$(echo "scale=0; $total_email_size_kb / 1024" | bc)
        email_size_display="$total_email_size_gb GB ($total_email_size_mb MB)"
    else
        total_email_size_mb=$(echo "scale=0; $total_email_size_kb / 1024" | bc)
        email_size_display="$total_email_size_mb MB"
    fi

    DEFAULT_PHP=$(whmapi1 php_get_system_default_version | awk '/system_default_php_version:/{print $2}')
    phpver=$(awk -v dom="$MAINDOMAIN" '
        $0 ~ "phpversion:" {
            ver=$2
        }
        END {
            if (ver == "" || ver == "inherit") {
                print ""
            } else {
                print ver
            }
        }' "$USERDATA_DIR/$MAINDOMAIN" 2>/dev/null)
    [[ -z "$phpver" ]] && phpver="$DEFAULT_PHP"

    mysql_version_full=$(get_mysql_version)
    mysql_version=$(echo "$mysql_version_full" | grep -oE '[0-9]+\.[0-9]+')

    db_info=$(get_database_details)
    db_details=($(echo "$db_info" | head -n -1))
    total_db_size_mb=$(echo "$db_info" | tail -n 1)

    nameservers=$(get_nameservers "$MAINDOMAIN")
    dns_records=$(get_dns_records "$MAINDOMAIN")

    if is_email_only_migration; then
        email_only_migration=true
    else
        email_only_migration=false
    fi

    precheck_results=(
        "Website Size: $website_size_display"
        "Email Accounts: $email_count"
        "Total Email Disk Usage: $email_size_display"
        "Databases: ${#db_details[@]}"
        "Total Database Size: $total_db_size_mb MB"
        "PHP Version: $phpver"
        "MySQL Version: $mysql_version_full"
    )

    if [ ${#big_mail_users[@]} -gt 0 ]; then
        precheck_results+=("Big Email Accounts (>10GB): ${#big_mail_users[@]}")
    fi

    precheck_results+=("Nameservers: $(echo $nameservers | tr '\n' ' ')")

    detailed_domain_status=()
    while IFS= read -r line; do
        if [[ -n "$line" ]]; then
            detailed_domain_status+=("$line")
        fi
    done <<< "$(echo -e "$all_domains_status")"

    detailed_db_info=()
    for db in "${db_details[@]}"; do
        detailed_db_info+=("  - $db")
    done

    detailed_email_info=()
    for email in "${big_mail_users[@]}"; do
        fixed_email=$(echo "$email" | awk -F'@' '{print $2"@"$1}')
        detailed_email_info+=("  - $fixed_email")
    done

    if [[ "$email_only_migration" == "true" ]]; then
        migration_ready="Yes (Email Only)"
        migration_message="Email-only migration (no working websites detected)"
        main_domain_status="Not Working (Email Only)"
    elif [[ "$main_domain_working" == "true" ]]; then
        migration_ready="Yes"
        migration_message="Main domain is working properly"
        main_domain_status="Working"
    else
        migration_ready="No"
        migration_message="Main domain is not working properly"
        main_domain_status="Not Working"
    fi

    if [[ "$addon_domains_exist" == "false" ]]; then
        addon_domains_status="No Addon Domains"
    elif [[ "$any_addon_not_working" == "false" ]]; then
        addon_domains_status="All Working"
    else
        addon_domains_status="Some Not Working"
    fi

    php_version_check=""
    if [[ "$migration_type" == "Shared to VPS" || "$migration_type" == "VPS to VPS" ]]; then
        php_version_num=$(normalize_php_version "$phpver")
        compare_result=$(compare_php_versions "$php_version_num" "8.0")

        if [[ "$compare_result" == "-1" ]]; then
            php_version_check="WARNING: PHP version $phpver is below the recommended 8.0 for VPS environments"
        fi
    fi
}

# Function to generate ticket notes
generate_ticket_notes() {
    echo -e "\n=== Migration Pre-Check Results ==="
    echo "cPanel username: $CPUSER"
    echo "Main Domain: $MAINDOMAIN"
    echo "Migration Type: $migration_type"
    echo ""
    echo "=== System Information ==="
    for result in "${precheck_results[@]}"; do
        echo "$result"
    done

    echo ""
    echo "=== Domain Status ==="
    for status in "${detailed_domain_status[@]}"; do
        echo "$status"
    done

    echo ""
    echo "=== DNS Records ==="
    echo -e "$dns_records"

    echo ""
    echo "=== Database Details ==="
    if [ ${#db_details[@]} -gt 0 ]; then
        for db in "${detailed_db_info[@]}"; do
            echo "$db"
        done
    else
        echo "No databases found"
    fi

    if [ ${#big_mail_users[@]} -gt 0 ]; then
        echo ""
        echo "=== Large Email Accounts (>10GB) ==="
        for email in "${detailed_email_info[@]}"; do
            echo "$email"
        done
    fi

    echo ""
    echo "=== Migration Readiness ==="
    echo "Main Domain Status: $main_domain_status"
    echo "Addon Domains Status: $addon_domains_status"
    echo "Migration Ready: $migration_ready"
    echo "Migration Message: $migration_message"

    if [[ -n "$php_version_check" ]]; then
        echo ""
        echo "=== PHP Version Check ==="
        echo "$php_version_check"
    fi

    if [[ -n "$mysql_compatibility_note" ]]; then
        echo ""
        echo "=== MySQL Compatibility Note ==="
        echo "$mysql_compatibility_note"
    fi
}

# Function to generate migration email for Shared to Shared
generate_shared_to_shared_email() {
    if [[ "$email_only_migration" == "true" ]]; then
        echo -e "\nSubject: Migration Prechecks Completed - Email Only Migration\n"
        echo "Greetings from the Migration Department."
        echo ""
        echo "We have received your migration request and will be coordinating with you throughout the email migration process."
        echo ""
        echo "Our prechecks indicate this appears to be an email-only migration (no working websites detected). Below are the prechecks and results:"
        echo ""
        echo "- Email Accounts: $email_count"
        echo "- Total Email Disk Usage: $email_size_display"

        if [ ${#big_mail_users[@]} -gt 0 ]; then
            echo ""
            echo "We have identified that your below email accounts are utilising more than 10GB of disk space."
            echo "In order to proceed with the migration, we kindly request that you reduce the size of your email account(s) to below 10GB."
            echo ""
            echo "Large Email Accounts:"
            for email in "${detailed_email_info[@]}"; do
                echo "$email"
            done
            echo ""
            echo "You can do this in one of the following ways:"
            echo ""
            echo "1. Remove Older Emails:"
            echo "   Access via cPanel:"
            echo "   cPanel > Email Accounts > Manage Email Disk Usage"
            echo ""
            echo "2. Download Emails via POP:"
            echo "   Configure your email client (e.g., Outlook, Thunderbird) to download and store emails using the POP protocol. Once downloaded, delete the emails from the server."
            echo ""
            echo "Please let us know once the account size is reduced, so we can proceed with the migration."
        else
            echo ""
            echo "We will proceed with the email migration. Please note:"
            echo "- The migration may take several hours depending on the email data size."
            echo ""
            echo "We will notify you once the migration is complete."
        fi
    elif [[ "$migration_ready" == "Yes" ]]; then
        if [ ${#big_mail_users[@]} -eq 0 ]; then
            echo -e "\nSubject: Migration Prechecks Completed - Proceeding with Migration\n"
            echo "Greetings from the Migration Department."
            echo ""
            echo "We have received your migration request and will be coordinating with you throughout the website and email migration process."
            echo ""
            echo "We are now beginning the migration. Please note that the process may take 6 hours or longer, depending on the overall disk usage of your account. Below are the prechecks and results:"
            echo ""
            for result in "${precheck_results[@]}"; do
                echo "- $result"
            done

            echo ""
            echo "Domain Status:"
            for status in "${detailed_domain_status[@]}"; do
                echo "  - $status"
            done

            if [ ${#db_details[@]} -gt 0 ]; then
                echo ""
                echo "Database Details:"
                for db in "${detailed_db_info[@]}"; do
                    echo "$db"
                done
            fi

            echo ""
            echo "PHP Version: $phpver (All PHP versions are supported in shared to shared migrations)"

            echo ""
            echo "We will update you as soon as the migration is complete."
            echo ""
            echo "Thank you for your cooperation."
        else
            echo -e "\nSubject: Action Required - Email Account Exceeding Allowed Limits\n"
            echo "Greetings from the Migration Department."
            echo ""
            echo "We have received your migration request and will be coordinating with you throughout the website and email migration process."
            echo ""
            echo "We have completed the pre-migration checks and identified that your below email accounts are utilising more than 10GB of disk space."
            echo "In order to proceed with the migration, we kindly request that you reduce the size of your email account(s) to below 10GB."
            echo ""
            echo "Large Email Accounts:"
            for email in "${detailed_email_info[@]}"; do
                echo "  - $email"
            done
            echo ""
            echo "You can do this in one of the following ways:"
            echo ""
            echo "1. Remove Older Emails:"
            echo "   Access via cPanel:"
            echo "   cPanel > Email Accounts > Manage Email Disk Usage"
            echo ""
            echo "2. Download Emails via POP:"
            echo "   Configure your email client (e.g., Outlook, Thunderbird) to download and store emails using the POP protocol. Once downloaded, delete the emails from the server."
            echo ""
            echo "Please let us know once the account size is reduced, so we can proceed with the migration."
        fi
    else
        echo -e "\nSubject: Action Required - Website Issues Detected\n"
        echo "Greetings from the Migration Department."
        echo ""
        echo "We have received your migration request and will be coordinating with you throughout the website and email migration process."
        echo ""
        echo "During the pre-migration checks, we found the following issues with your websites:"
        echo ""
        echo "$migration_message"
        echo ""
        echo "Domain Status:"
        for status in "${detailed_domain_status[@]}"; do
            echo "  - $status"
        done
        echo ""
        if [ ${#big_mail_users[@]} -gt 0 ]; then
            echo "Additionally, we have identified that your below email accounts are utilising more than 10GB of disk space."
            echo "In order to proceed with the migration, we kindly request that you reduce the size of your email account(s) to below 10GB."
            echo ""
            echo "Large Email Accounts:"
            for email in "${detailed_email_info[@]}"; do
                echo "  - $email"
            done
            echo ""
            echo "You can do this in one of the following ways:"
            echo ""
            echo "1. Remove Older Emails:"
            echo "   Access via cPanel:"
            echo "   cPanel > Email Accounts > Manage Email Disk Usage"
            echo ""
            echo "2. Download Emails via POP:"
            echo "   Configure your email client (e.g., Outlook, Thunderbird) to download and store emails using the POP protocol. Once downloaded, delete the emails from the server."
            echo ""
        fi
        echo "Please get back to us once these issues are addressed, so we can proceed with your migration."
    fi

    echo ""
    echo "Regards,"
    echo "Migration Team"
}

# Function to generate VPS migration email
generate_vps_email() {
    echo -e "\nSubject: VPS Migration Prechecks Completed\n"
    echo "Greetings from the Migration Department."
    echo ""
    echo "We have received your VPS migration request and will be coordinating with you throughout the migration process."
    echo ""
    echo "Below are the prechecks and results:"
    echo ""
    echo "=== Source Server Information ==="
    echo "OS: $source_os"
    echo "Disk Space: ${source_disk_gb}GB"
    echo "Memory: ${source_mem_gb}GB"
    echo "Backup Size: $backup_size"
    echo ""
    echo "=== Destination Server Information ==="
    echo "OS: $dest_os"
    echo "Disk Space: ${dest_disk_gb}GB"
    echo "Memory: ${dest_mem_gb}GB"
    echo "MySQL Version: $dest_mysql_full"
    echo "Minimum PHP Version: $dest_php_version"
    echo ""
    
    # Check for potential issues
    if (( $(echo "$source_disk_gb > $dest_disk_gb" | bc -l) )); then
        echo "⚠️ Warning: Source server uses more disk space (${source_disk_gb}GB) than destination has available (${dest_disk_gb}GB)"
    fi
    
    if (( $(echo "$source_mem_gb > $dest_mem_gb" | bc -l) )); then
        echo "⚠️ Warning: Source server has more memory (${source_mem_gb}GB) than destination (${dest_mem_gb}GB)"
    fi
    
    echo ""
    echo "We will now proceed with the migration. Please note:"
    echo "- The migration may take several hours depending on the data size"
    echo "- We will notify you once the migration is complete"
    echo "- After migration, please verify all services are working as expected"
    echo ""
    echo "Regards,"
    echo "Migration Team"
}

# Function to collect user information
collect_info() {
    if [ "$migration_type" = "VPS to VPS" ]; then
        get_system_info
    fi

    read -rp "Enter the cPanel username: " CPUSER
    USER_HOME=$(grep -i "^$CPUSER:" /etc/passwd | cut -d: -f6)
    if [ ! -d "$USER_HOME" ]; then
        echo "Error: Home directory for $CPUSER not found."
        exit 1
    fi

    CPDATA_DIR="/var/cpanel/users/$CPUSER"
    MYSQL_DIR="/var/lib/mysql"
    USERDATA_DIR="/var/cpanel/userdata/$CPUSER"
    MAINDOMAIN=$(grep -i ^DNS= "$CPDATA_DIR" | cut -d= -f2)
}

# Main script execution
while true; do
    show_menu
    case $choice in
        1)
            migration_type="Shared to Shared"
            collect_info
            perform_prechecks
            generate_ticket_notes
            generate_shared_to_shared_email
            echo -e "\nMigration precheck completed."
            ;;
        2)
            migration_type="Shared to VPS"
            collect_info
            perform_prechecks
            generate_ticket_notes
            generate_vps_email
            echo -e "\nMigration precheck completed."
            ;;
        3)
            migration_type="VPS to VPS"
            collect_info_vps
            generate_vps_migration_report
            echo -e "\nMigration precheck completed."
            ;;
        4)
            echo "Exiting..."
            exit 0
            ;;
        *)
            echo "Invalid option. Please try again."
            sleep 2
            ;;
    esac

    read -rp "Press Enter to continue..."
done
