#!/bin/bash

# PHP API的URL
API_URL="https://www.xiaoweio.com/tools/counter/index.php"

# 获取当前计数
get_count() {
    local response=$(curl -s "$API_URL?action=get_count")
    local count=$(echo "$response" | sed -n 's/.*"count":\s*\([0-9]*\).*/\1/p')
    echo "+----------------------------------------------------------------------"
    echo "| 源支付 (iPad/iMac) 微信云端一键安装脚本"
    echo "+----------------------------------------------------------------------"
    echo "| Copyright © 2022-2023(https://www.zunfox.com) All rights reserved."
    echo "+----------------------------------------------------------------------"
    echo "| 本脚本由尊狐云提供  当前脚本执行次数: $count"
    echo "+----------------------------------------------------------------------"
}

# 增加计数
increment_count() {
    local response=$(curl -s -X POST "$API_URL" -d "action=increment_count")
    local message=$(echo "$response" | sed -n 's/.*"message":\s*"\([^"]*\)".*/\1/p')
    # echo "$message"
}

# 配置
DOCKER_IMAGE_YPAYIPAD="registry.cn-hangzhou.aliyuncs.com/zunfox/ypayipad"
DOCKER_IMAGE_YPAYIMAC="registry.cn-hangzhou.aliyuncs.com/zunfox/ypayimac"

# 函数：自动更换软件源为华为云源
change_to_huawei_cloud_source() {
    local distro="$1"
    case "$distro" in
        "centos")
            local centos_version=$(rpm -q --qf "%{VERSION}" $(rpm -q --whatprovides redhat-release))
            if [ "$centos_version" == "8" ]; then
                # CentOS 8 更换为阿里云源的命令
                sudo dnf install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm
                sudo dnf config-manager --set-enabled PowerTools
                sudo dnf config-manager --set-enabled epel
            else
                # CentOS 7 更换为华为云源的命令
                sudo yum clean all
                sudo yum makecache
                sudo yum -y install epel-release
                sudo yum -y install https://mirrors.huaweicloud.com/docker-ce/linux/centos/7/x86_64/stable/Packages/docker-ce-cli-19.03.15-3.el7.x86_64.rpm https://mirrors.huaweicloud.com/docker-ce/linux/centos/7/x86_64/stable/Packages/docker-ce-19.03.15-3.el7.x86_64.rpm
            fi
            ;;
        "ubuntu")
            # Ubuntu 更换为华为云源的命令
            sudo sed -i 's/archive.ubuntu.com/mirrors.huaweicloud.com/g' /etc/apt/sources.list
            ;;
        "debian")
            # Debian 更换为华为云源的命令
            sudo sed -i 's/deb.debian.org/mirrors.huaweicloud.com/g' /etc/apt/sources.list
            ;;
        *)
            echo "不支持的发行版，无法更换软件源。"
            ;;
    esac
}

# 函数：安装Docker
install_docker() {
    local distro="$1"
    if [ "$distro" == "centos" ]; then
        # CentOS 安装Docker的步骤
        sudo yum remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine
        sudo yum install -y yum-utils device-mapper-persistent-data lvm2
        sudo yum-config-manager --add-repo https://mirrors.huaweicloud.com/docker-ce/linux/centos/docker-ce.repo
        sudo yum install -y docker-ce docker-ce-cli containerd.io
        sudo systemctl start docker
        sudo systemctl enable docker
    elif [ "$distro" == "ubuntu" ]; then
        # Ubuntu 安装Docker的步骤
        sudo apt-get update
        sudo apt-get remove -y docker docker-engine docker.io containerd runc
        sudo apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common
        sudo curl -fsSL https://mirrors.huaweicloud.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
        echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.huaweicloud.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
        sudo apt-get update
        sudo apt-get install -y docker-ce docker-ce-cli containerd.io
        sudo systemctl start docker
        sudo systemctl enable docker
    elif [ "$distro" == "debian" ]; then
        # Debian 安装Docker的步骤
        sudo apt-get update
        sudo apt-get remove -y docker docker-engine docker.io containerd runc
        sudo apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common
        sudo curl -fsSL https://mirrors.huaweicloud.com/docker-ce/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
        echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.huaweicloud.com/docker-ce/linux/debian $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
        sudo apt-get update
        sudo apt-get install -y docker-ce docker-ce-cli containerd.io
        sudo systemctl start docker
        sudo systemctl enable docker
    else
        echo "不支持的发行版，请手动安装Docker。"
        exit 1
    fi
}

# 函数：检查Docker是否已安装
check_docker_installed() {
    if [ -x "$(command -v docker)" ]; then
        return 0
    else
        return 1
    fi
}

# 函数：检查Docker容器是否已存在
check_docker_container_exists() {
    local container_name="$1"
    if docker ps -a --format '{{.Names}}' | grep -q "$container_name"; then
        return 0
    else
        return 1
    fi
}

# 函数：删除Docker容器
delete_docker_container() {
    local container_name="$1"
    docker stop "$container_name" > /dev/null
    docker rm "$container_name" > /dev/null
    echo "旧容器 $container_name 已删除。"
}

# 函数：检查Docker镜像是否存在，如果不存在则下载
pull_docker_image() {
    local image_name="$1"
    if ! docker image inspect "$image_name" &> /dev/null; then
        echo "开始下载镜像 $image_name..."
        docker pull "$image_name"
        echo "镜像下载完成！"
    else
        echo "镜像 $image_name 已经存在，跳过下载过程。"
    fi
}

# 函数：生成随机端口
generate_random_port() {
    local min_port="$1"
    local max_port="$2"
    shuf -i "$min_port"-"$max_port" -n 1
}

# 函数：运行Docker容器
run_docker_container() {
    local container_name="$1"
    local image_name="$2"
    local internal_port="$3"
    
    # 检查容器是否已存在
    if check_docker_container_exists "$container_name"; then
        echo "容器 $container_name 已存在，请删除旧容器后再运行。"
        read -p "是否删除旧容器 $container_name 并继续？(y/N) " delete_container_choice
        if [[ $delete_container_choice == "Y" || $delete_container_choice == "y" ]]; then
            delete_docker_container "$container_name"
        else
            echo "操作取消，退出脚本。"
            exit 1
        fi
    fi

    # 生成随机端口或使用用户自定义的端口
    local external_port
    if [[ $customize_ports == "Y" || $customize_ports == "y" ]]; then
        read -p "请输入自定义的映射端口（$container_name 端口）: " external_port
    else
        external_port=$(generate_random_port 20000 65535)
    fi

    # 运行容器并映射端口
    docker run -d -p "$external_port:$internal_port" --name "$container_name" "$image_name"
    echo "容器 $container_name 已成功运行并映射外部端口：$external_port"
}

# 主程序


# 增加计数
increment_count
# 打印当前计数
get_count


# 读取发行版信息
if [ -f /etc/os-release ]; then
    source /etc/os-release
    DISTRO=$(echo "$ID" | tr '[:upper:]' '[:lower:]')
else
    echo "无法获取发行版信息，请手动安装Docker。"
    exit 1
fi

# 询问用户是否更换软件源为华为云源
read -p "是否更换软件源为华为云源？(Y/n) " change_to_huawei_cloud_choice
change_to_huawei_cloud_choice=${change_to_huawei_cloud_choice:-"Y"}  # 默认为空时为确定（"Y"）
echo "您选择了：$change_to_huawei_cloud_choice"

if [[ $change_to_huawei_cloud_choice == "Y" || $change_to_huawei_cloud_choice == "y" ]]; then
    # 自动更换软件源为华为云源
    change_to_huawei_cloud_source "$DISTRO"
fi

# 安装Docker
if ! check_docker_installed; then
    read -p "是否安装Docker？(Y/n) " install_docker_choice
    install_docker_choice=${install_docker_choice:-"Y"}  # 默认为空时为确定（"Y"）
    echo "您选择了：$install_docker_choice"
    
    if [[ $install_docker_choice == "Y" || $install_docker_choice == "y" ]]; then
        echo "开始安装Docker..."
        install_docker "$DISTRO"
    else
        echo "操作取消，退出脚本。"
        exit 1
    fi
fi

# 检查并下载Docker镜像
pull_docker_image "$DOCKER_IMAGE_YPAYIPAD"
pull_docker_image "$DOCKER_IMAGE_YPAYIMAC"

# 询问用户是否自定义映射端口
read -p "是否自定义映射端口？(Y/n) " customize_ports
customize_ports=${customize_ports:-"Y"}  # 默认为空时为确定（"Y"）
echo "您选择了：$customize_ports"

# 运行Docker容器
run_docker_container "ypayipad" "$DOCKER_IMAGE_YPAYIPAD" "4000"
run_docker_container "ypayimac" "$DOCKER_IMAGE_YPAYIMAC" "82"