#!/bin/bash
echo "FlexCDN Installer v1.1.1 by Nyarime"

# 判断本机的CPU架构和操作系统版本
cpu_arch=$(uname -m)
os_version=$(grep '^PRETTY_NAME' /etc/os-release | cut -d '"' -f 2)
echo "本机CPU架构：$cpu_arch"
echo "本机操作系统版本：$os_version"

# 安装sudo
    if [[ "$os_version" == *"Ubuntu"* || "$os_version" == *"Debian"* ]]; then
        apt-get install -y sudo
    elif [[ "$os_version" == *"CentOS"* || "$os_version" == *"Red Hat"* || "$os_version" == *"Fedora"* ]]; then
        yum install -y sudo
    else
        echo "未知的操作系统类型，无法安装 sudo"
        exit 1
    fi

# 安装依赖函数
install_package() {
    local package=$1
    if [[ "$os_version" == *"Ubuntu"* || "$os_version" == *"Debian"* ]]; then
        sudo apt-get install -y "$package"
    elif [[ "$os_version" == *"CentOS"* || "$os_version" == *"Red Hat"* || "$os_version" == *"Fedora"* ]]; then
        sudo yum install -y "$package"
    else
        echo "未知的操作系统类型，无法安装 $package"
        exit 1
    fi
}

# 检查并安装 unzip
for pkg in unzip; do
    if ! command -v "$pkg" &> /dev/null; then
        echo "$pkg 未安装，正在安装..."
        install_package "$pkg"
    else
        echo "$pkg 已安装"
    fi
done

# 检查 /usr/local/cloud 目录是否存在
if [ ! -d "/usr/local/cloud" ]; then
    sudo mkdir -p /usr/local/cloud
    echo "安装目录创建成功：/usr/local/cloud"
else
    echo "检测到 /usr/local/cloud 已存在，可能已安装过 FlexCDN，脚本退出！"
    exit 1
fi

# 修改本机 hosts 以屏蔽官方域名
if ! grep -q "127.0.0.1 flexcdn.cn" /etc/hosts; then
    echo "127.0.0.1 flexcdn.cn" | sudo tee -a /etc/hosts
    echo "已成功屏蔽官方域名通信！"
fi

# 下载并解压架构对应的程序包
cd /usr/local/cloud || exit 1
case "$cpu_arch" in
    x86_64)
        wget https://dl.naixi.net/cdn/flexcdn/1.1.1/cloud-admin-linux-amd64-v1.1.1.zip
        ;;
    aarch64)
        wget https://dl.naixi.net/cdn/flexcdn/1.1.1/cloud-admin-linux-arm64-v1.1.1.zip
        ;;
    *)
        echo "不支持的CPU架构：$cpu_arch"
        exit 1
        ;;
esac
unzip -o cloud-admin-linux-*.zip
chmod +x /usr/local/cloud/cloud-admin/cloud-api/bin/cloud-api
# 启动 cloud-admin 主程序并安装服务
cd cloud-admin || exit 1
bin/cloud-admin start
bin/cloud-admin service

# 输出管理平台地址及注册码
clear
ipv4_address=$(curl -s ipv4.ip.sb)
ipv6_address=$(curl -s ipv6.ip.sb)

echo -e "\033[1;33m执行完毕！请通过浏览器访问 http://$ipv4_address:8000/ 或 http://$ipv6_address:8000/ 进入管理平台，并依据页面提示完成最后的安装流程！\033[0m"
echo -e "\033[1;33m如果无法访问，请检查防火墙是否开放8000端口！\033[0m"
echo -e "-------------"
echo -e "如需激活商业功能，请在管理平台依次点击「系统设置」>「商业版本」>「申请」，提供申请码并购买："
echo -e "请使用Telegram联系 https://t.me/BaiPiaoZhenXiang 购买，购买时请附带申请码，感谢合作！"
echo -e "如有问题请反馈至奶昔论坛 https://forum.naixi.net/thread-5352-1-1.html"
