#!/bin/bash
echo "FlexCDN v1.0.4 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"
# 安装依赖函数
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
}
# 检查并安装 sudo 和 unzip
for pkg in sudo 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://downloads.658734.xyz/flexcdn/amd64/cloud-admin-linux-amd64-plus-v1.0.4.zip
        ;;
    aarch64)
        wget https://downloads.658734.xyz/flexcdn/arm64/cloud-admin-linux-arm64-plus-v1.0.4.zip
        ;;
    *)
        echo "不支持的CPU架构：$cpu_arch"
        exit 1
        ;;
esac

# 解压文件
echo "解压安装包..."
unzip -o cloud-admin-linux-*.zip

# 修复1：先设置所有目录的权限
echo "设置目录权限..."
find /usr/local/cloud -type d -exec chmod 755 {} \;

# 修复2：专门设置所有二进制文件的可执行权限
echo "设置可执行文件权限..."
find /usr/local/cloud -type f -path "*/bin/*" -exec chmod +x {} \;
# 特别确保cloud-admin主程序有执行权限
if [ -f "/usr/local/cloud/cloud-admin/bin/cloud-admin" ]; then
    chmod +x /usr/local/cloud/cloud-admin/bin/cloud-admin
    echo "已设置cloud-admin主程序执行权限"
else
    echo "警告：未找到cloud-admin主程序，请检查安装包是否完整"
    exit 1
fi

# 验证权限设置是否成功
echo "验证权限设置："
ls -la /usr/local/cloud/cloud-admin/bin

# 切换到cloud-admin目录
cd cloud-admin || exit 1

# 启动cloud-admin主程序并安装服务
echo "启动cloud-admin服务..."
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 "[payload removed: 336 characters]"
echo -e "本脚本来自： https://flex.dd.ci，皓宇博客二次修改（仅修改下载源）"