#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8
setup_path=/www

# ========== 日志函数 ==========
log() {
    echo -e "$1"
}

error_exit() {
    log "ERROR! $1"
    exit 1
}

# ========== 宝塔服务控制 ==========
stop_bt_services() {
    log "Stopping BT Panel and related services..."
    /etc/init.d/bt stop >/dev/null 2>&1

    for svc in nginx httpd mysqld pure-ftpd tomcat redis memcached; do
        [ -f "/etc/init.d/$svc" ] && /etc/init.d/$svc stop >/dev/null 2>&1
    done

    # PHP-FPM versions
    for ver in 52 53 54 55 56 70 71 72 73 74 80 81 82 83; do
        [ -f "/etc/init.d/php-fpm-$ver" ] && /etc/init.d/php-fpm-$ver stop >/dev/null 2>&1
    done

    rm -f /www/server/panel/data/502Task.pl
}

start_bt_services() {
    log "Starting BT Panel and related services..."
    /etc/init.d/bt start >/dev/null 2>&1

    for svc in nginx httpd mysqld pure-ftpd tomcat redis memcached; do
        [ -f "/etc/init.d/$svc" ] && /etc/init.d/$svc start >/dev/null 2>&1
    done

    for ver in 52 53 54 55 56 70 71 72 73 74 80 81 82 83; do
        [ -f "/etc/init.d/php-fpm-$ver" ] && /etc/init.d/php-fpm-$ver start >/dev/null 2>&1
    done

    touch /www/server/panel/data/502Task.pl
}

# ========== 检测逻辑 ==========
detect_disks() {
    sysDisk=$(cat /proc/partitions | grep -v name | grep -v ram | awk '{print $4}' | grep -v '^$' | grep -v '[0-9]$' | grep -v 'vda' | grep -v 'xvda' | grep -v 'sda' | grep -E '(vd|sd|xvd)' || true)
    if [ -z "$sysDisk" ]; then
        error_exit "This server has only one hard drive. Cannot proceed.\n此服务器只有一块磁盘，无法挂载。"
    fi
}

check_already_mounted() {
    if df -h | awk '{print $6}' | grep -q "^${setup_path}$"; then
        error_exit "Directory $setup_path is already mounted. Exiting."
    fi
}

check_windows_partition() {
    if fdisk -l 2>/dev/null | grep -qiE "NTFS|FAT32"; then
        log "Warning: Windows partition detected. For data safety, please mount manually."
        exit 1
    fi
}

# ========== 挂载后验证可写性 ==========
verify_writable() {
    local mp="$1"
    mkdir -p "$mp"
    if ! echo "test" > "$mp/.mount_test" 2>/dev/null; then
        error_exit "Mount point $mp is not writable. Aborting."
    fi
    rm -f "$mp/.mount_test"
}

# ========== 功能1：挂载已有 ext4 分区 ==========
mount_existing_partition() {
    log "\n[Mode] Mounting existing ext4 partition to $setup_path\n"
    disks=$(cat /proc/partitions | grep -v name | grep -v ram | awk '{print $4}' | grep -v '^$' | grep -v '[0-9]$' | grep -v 'vda' | grep -v 'xvda' | grep -v 'sda' | grep -E '(vd|sd|xvd)')

    for disk in $disks; do
        part="/dev/${disk}1"
        log "Checking: $part"

        if ! fdisk -l "/dev/$disk" 2>/dev/null | grep -q "$part"; then
            continue
        fi

        if df -P | grep -q "$part"; then
            log "Already mounted. Skipping."
            continue
        fi

        mkdir -p "$setup_path"
        if mount "$part" "$setup_path"; then
            sed -i "\|^$part|d" /etc/fstab
            echo "$part    $setup_path    ext4    defaults    0 0" >> /etc/fstab
            verify_writable "$setup_path"
            log "✅ Mounted $part to $setup_path"
            return 0
        else
            log "Failed to mount $part (not ext4?)"
        fi
    done
    error_exit "No valid ext4 partition found."
}

# ========== 功能2：格式化并挂载 ==========
format_and_mount_disk() {
    log "\n[Mode] Formatting and mounting new disk to $setup_path\n"
    disks=$(cat /proc/partitions | grep -v name | grep -v ram | awk '{print $4}' | grep -v '^$' | grep -v '[0-9]$' | grep -v 'vda' | grep -v 'xvda' | grep -v 'sda' | grep -E '(vd|sd|xvd)')

    for disk in $disks; do
        dev="/dev/$disk"
        part="${dev}1"

        log "Processing disk: $dev"

        # Skip if already partitioned
        if fdisk -l "$dev" 2>/dev/null | grep -v bytes | grep -q "${disk}[1-9]"; then
            log "Disk $dev already partitioned. Skipping format."
            continue
        fi

        # Partition
        log "Creating partition on $dev..."
        fdisk -S 56 "$dev" << EOF
n
p
1


wq
EOF
        sleep 5

        if ! fdisk -l "$dev" | grep -q "$part"; then
            log "Partition failed."
            continue
        fi

        # Format
        log "Formatting $part as ext4..."
        if ! mkfs.ext4 -F "$part"; then
            log "Format failed."
            continue
        fi

        # Mount
        mkdir -p "$setup_path"
        sed -i "\|^$part|d" /etc/fstab
        echo "$part    $setup_path    ext4    defaults    0 0" >> /etc/fstab
        if mount -a; then
            verify_writable "$setup_path"
            log "✅ Formatted and mounted $part to $setup_path"
            return 0
        else
            log "Mount via fstab failed."
        fi
    done
    error_exit "Failed to format and mount any disk."
}

# ========== 主流程 ==========
main() {
    detect_disks
    check_already_mounted
    check_windows_partition

    # 判断是否安装宝塔
    bt_installed=false
    if [ -f "/etc/init.d/bt" ] && [ -f "/www/server/panel/data/port.pl" ]; then
        bt_installed=true
        log "Detected BT Panel installation. Data migration will be performed."
    else
        log "BT Panel not detected. Only mounting disk (no data migration)."
    fi

    # 确定模式
    mode=""
    if [[ "$1" == "--mount-only" ]]; then
        mode="mount"
    elif [[ "$1" == "--format-and-mount" ]]; then
        mode="format"
    else
        echo
        echo "+----------------------------------------------------------------------+"
        echo "| Choose operation mode:                                               |"
        echo "|   1) Mount existing ext4 partition (no format)                       |"
        echo "|   2) Format new disk and mount (ERASES ALL DATA!)                    |"
        echo "+----------------------------------------------------------------------+"
        while [[ "$choice" != "1" && "$choice" != "2" ]]; do
            read -p "Enter choice (1 or 2): " choice
        done
        [[ "$choice" == "1" ]] && mode="mount" || mode="format"
    fi

    # 如果是宝塔环境，先备份 /www
    if $bt_installed; then
        # 检查磁盘空间是否足够
        disk=$(echo "$sysDisk" | head -1)
        diskFree=$(cat /proc/partitions | grep "$disk" | awk '{print $3}')
        wwwUse=$(du -sk /www 2>/dev/null | awk '{print $1}')
        if [ -z "$wwwUse" ]; then wwwUse=0; fi

        if [ "$diskFree" -lt "$wwwUse" ]; then
            error_exit "Data disk too small ($diskFree KB) vs /www usage ($wwwUse KB). Cannot migrate."
        fi

        log "\n🛑 Stopping BT services..."
        stop_bt_services
        log "📦 Backing up /www to /bt-backup..."
        mv /www /bt-backup
    fi

    # 执行挂载
    if [[ "$mode" == "mount" ]]; then
        mount_existing_partition
    else
        format_and_mount_disk
    fi

    # 如果是宝塔环境，恢复数据
    if $bt_installed; then
        log "🚚 Migrating data from /bt-backup to /www..."
        cp -r -p -a /bt-backup/* /www/
        log "✅ Data migration completed."

        log "🟢 Starting BT services..."
        start_bt_services
    fi

    log "\n🎉 All done! Mounted at $setup_path"
    df -h "$setup_path"
}

# ========== 入口 ==========
main "$@"