#!/bin/bash

if [ $1 = "-h" ] || [ $1 = "--help" ]; then
    echo "Usage: $0 <username> <up_bandwidth> [isp]"
    echo "Example: $0 test 100 telecom"
    echo "up_bandwidth must be greater than 20"
    echo "Supported ISPs: telecom, unicom, mobile, default is unicom"
    exit 0
fi

if [ $# -ne 2 ] && [ $# -ne 3 ]; then
    echo "Usage: $0 <username> <up_bandwidth> [isp]"
    exit 1
elif ! [[ $2 =~ ^[0-9]+$ ]]; then
    echo "${2}: up_bandwidth must be a number"
    exit 1
elif [ $2 -lt 20 ]; then
    echo "${2}: up_bandwidth must be greater than 20"
    exit 1
elif [ $# -eq 3 ] && [ $3 != "telecom" ] && [ $3 != "unicom" ] && [ $3 != "mobile" ]; then
    echo "${3}: invalid isp"
    echo "Supported ISPs: telecom, unicom, mobile, default is unicom"
    exit 1
fi

username=${1}
up_bandwidth=${2}

info() {
    echo -e "\033[32m${1}\033[0m"
}

error() {
    echo -e "\033[31m${1}\033[0m"
}

info "--[ stopping old services ]--"
systemctl disable armbian-flank-config.service
systemctl disable --now armbian.service
systemctl disable --now flank.service
systemctl disable --now ping-getway.service
systemctl disable --now check-network.service
systemctl disable --now netbox_daemon.service
systemctl disable --now blink.service
systemctl disable --now niulinkd.service
crontab -r
if [ -n "$(docker ps -q)" ]; then
    docker stop $(docker ps -q)
    docker rm $(docker ps -aq)
fi
killall -9 frp_agent DownTask frpc

BACKUP_FILE="/etc/crontab.bak"
if [ ! -f "$BACKUP_FILE" ]; then
    cp /etc/crontab "$BACKUP_FILE"
fi
head -n 17 /etc/crontab > /etc/crontab.tmp
if [ $? -eq 0 ]; then
    mv /etc/crontab.tmp /etc/crontab
fi
chmod 644 /etc/crontab
chown root:root /etc/crontab

systemctl restart cron

cat /etc/ssh/sshd_config | grep -v "ListenAddress" > /etc/ssh/sshd_config.tmp
mv /etc/ssh/sshd_config.tmp /etc/ssh/sshd_config
echo "ListenAddress 127.0.0.1" >> /etc/ssh/sshd_config
systemctl restart sshd


info "--[ creating user pear ]--"
useradd -G sudo -U -m -s /usr/bin/bash pear
echo -e "Pear@123456\nPear@123456" | passwd pear
echo -e "Pear@123456\nPear@123456" | passwd flank
echo -e "Pear@123456\nPear@123456" | passwd root

info "--[ downloading openfog ]--"
curl -k -o /tmp/openfog.tar.gz https://download.openfogos.com/spare/fogvdn_PEAR_ARM64_LINUX_639.tar.gz
if [ $? -ne 0 ]; then
    error "Download failed"
    exit 1
fi

info "--[ installing openfog ]--"
tar -zxf /tmp/openfog.tar.gz -C /
/etc/pear/pear_update/post_command.sh > /dev/null 2>&1
curl -s https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh | bash
apt-get install speedtest nftables nload bash-completion iperf3 stun-client -y

info "--[ remounting disk ]--"
curl -k -o /root/pear/pear_remount.sh https://download.openfogos.com/spare/pear_remount.sh
chmod +x /root/pear/pear_remount.sh
# sed -i "s/bash \/bin\/bly\/flank-mount.sh/bash \/root\/pear\/pear_remount.sh/g" /etc/rc.local
echo -e "nohup /root/pear/pear_remount.sh &\nexit 0\n" > /etc/rc.local

MOUNT_POINT=$(df | grep /dev/sda | awk '{print $6}')
if [ -n "$MOUNT_POINT" ]; then
    echo "Attempting to unmount $MOUNT_POINT..."

    # 查找占用挂载点的进程
    echo "Finding processes using $MOUNT_POINT..."
    lsof_output=$(lsof +D "$MOUNT_POINT" 2>/dev/null)

    if [ -n "$lsof_output" ]; then
        echo "Processes using $MOUNT_POINT:"
        echo "$lsof_output"
        echo "Killing processes..."
        # 杀死占用的进程
        while read -r pid; do
            echo "Killing process $pid..."
            kill -9 "$pid"
        done < <(echo "$lsof_output" | awk 'NR>1 {print $2}')
    fi

    # 检查是否有子挂载点
    echo "Checking for submounts..."
    submounts=$(findmnt -n -o TARGET | grep -E "^$MOUNT_POINT/[^ ]+")
    if [ -z "$submounts" ]; then
        echo "No submounts found under $MOUNT_POINT."
    else
        echo "Unmounting submounts..."
        while read -r submount; do
            echo "Unmounting $submount..."
            umount -l "$submount"
        done <<< "$submounts"
    fi

    # 尝试强制卸载
    echo "Attempting to force unmount $MOUNT_POINT..."
    if umount -l "$MOUNT_POINT"; then
        echo "Successfully unmounted $MOUNT_POINT."
    else
        error "Failed to unmount $MOUNT_POINT."
        exit 1
    fi
else
    echo "No mount point found for /dev/sda."
fi

if [ -d "/data0" ]; then
    rm -rf /data0/*
fi
wipefs -a /dev/sda
mkfs.ext4 -F -F /dev/sda
if [ $? -ne 0 ]; then
    error "Format failed"
    exit 1
fi
nohup /root/pear/pear_remount.sh &

info "--[ setting dmz ]--"
echo dmz > /bin/bly/nat_model
curl -s bly.cool:82/armbian/dmz.sh | bash

info "--[ generating config ]--"
mkdir -p /etc/pear/pear_monitor
timestamp=$(date +%s)
isp=""
if [ $# -eq 3 ]; then
    case $3 in
        telecom)
            isp="电信"
            ;;
        unicom)
            isp="联通"
            ;;
        mobile)
            isp="移动"
            ;;
    esac
else
    isp="联通"
fi
echo "{
    \"user_marked\": {
        \"username\": \"${username}\",
        \"isp\": \"${isp}\",
        \"per_line_up_bw\": ${up_bandwidth},
        \"mtime\": ${timestamp}
    },
    \"nics\": [
        \"eth0\"
    ],
    \"storage\": [
        \"/data0\"
    ]
}" > /etc/pear/pear_monitor/config.json

info "--[ starting services ]--"
systemctl enable pear_init.service
systemctl enable xc_cdn.service
systemctl start xc_cdn.service

info "--[ done ]--"

exit 0
