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

# 设置默认挂载目录为 /www，如果提供了参数则使用该参数
setup_path=${1:-/www}

# 检测目标目录是否已挂载磁盘
mountDisk=$(df -h | awk '{print $6}' | grep "${setup_path}")
if [ -n "${mountDisk}" ]; then
    echo "Directory ${setup_path} has been mounted, exit."
    exit 1
fi

# 检测磁盘数量
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' -e 'sd' -e 'xvd')
if [ -z "${sysDisk}" ]; then
    echo "ERROR! This server has only one hard drive, exit."
    exit 1
fi

# 检测是否有windows分区
winDisk=$(fdisk -l | grep "NTFS\|FAT32")
if [ -n "${winDisk}" ]; then
    echo 'Warning: Windows partition detected. Mount manually for data security.'
    exit 1
fi

echo "Starting disk partitioning and mounting process..."

# 分区和挂载函数
processDisk() {
    for disk in ${sysDisk}; do
        mountPoint="/dev/${disk}1"

        # 检查分区是否已经存在
        if fdisk -l /dev/${disk} | grep -q "${mountPoint}"; then
            # 检查分区格式
            fsType=$(blkid -o value -s TYPE ${mountPoint})
            if [ "${fsType}" = "ext4" ] || [ "${fsType}" = "xfs" ]; then
                echo "Mounting ${mountPoint} to ${setup_path}..."
                mkdir -p ${setup_path}
                sed -i "/${mountPoint}/d" /etc/fstab
                echo "${mountPoint}    ${setup_path}    ${fsType}    defaults    0 0" >> /etc/fstab
                mount -a
                df -h
            else
                echo "Skipping ${mountPoint}, not a supported filesystem type."
            fi
        else
            # 如果没有分区，则进行分区
            echo "Partitioning /dev/${disk}..."
            echo -e "n\np\n1\n\n\nw" | fdisk /dev/${disk}
            sleep 5

            # 检查分区是否成功
            if fdisk -l /dev/${disk} | grep -q "${mountPoint}"; then
                echo "Formatting ${mountPoint}..."
                mkfs.ext4 ${mountPoint}
                mkdir -p ${setup_path}
                sed -i "/${mountPoint}/d" /etc/fstab
                echo "${mountPoint}    ${setup_path}    ext4    defaults    0 0" >> /etc/fstab
                mount -a
                df -h
            fi
        fi
    done
}

# 执行分区和挂载
processDisk