#!/bin/bash

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

# 检查并安装sudo
if ! command -v sudo &> /dev/null; then
    echo "sudo未安装，正在安装..."
    if [[ "$os_version" == *"Ubuntu"* || "$os_version" == *"Debian"* ]]; then
        apt-get install sudo -y
    elif [[ "$os_version" == *"CentOS"* || "$os_version" == *"Red Hat"* || "$os_version" == *"Fedora"* ]]; then
        yum install sudo -y
    fi
else
    echo "sudo已安装"
fi

# 更新软件包列表
if [[ "$os_version" == *"Ubuntu"* || "$os_version" == *"Debian"* ]]; then
    echo "检测到系统类型为Debian/Ubuntu，正在更新软件包列表..."
    sudo apt-get update -y
elif [[ "$os_version" == *"CentOS"* || "$os_version" == *"Red Hat"* || "$os_version" == *"Fedora"* ]]; then
    echo "检测到系统类型为CentOS/Red Hat/Fedora，正在更新软件包列表..."
    sudo yum update -y
else
    echo "无法识别的操作系统类型。"
    exit 1
fi

# 检查并安装unzip
if ! command -v unzip &> /dev/null; then
    echo "unzip未安装，正在安装..."
    if [[ "$os_version" == *"Ubuntu"* || "$os_version" == *"Debian"* ]]; then
        sudo apt install unzip -y
    elif [[ "$os_version" == *"CentOS"* || "$os_version" == *"Red Hat"* || "$os_version" == *"Fedora"* ]]; then
        sudo yum install unzip -y
    fi
else
    echo "unzip已安装"
fi

# 修改本机hosts屏蔽官方域名
hosts_entries=(
    "127.0.0.1 goedge.cn"
    "127.0.0.1 goedge.cloud"
    "127.0.0.1 dl.goedge.cloud"
    "127.0.0.1 dl.goedge.cn"
    "127.0.0.1 global.dl.goedge.cloud"
    "127.0.0.1 global.dl.goedge.cn"
)

for entry in "${hosts_entries[@]}"; do
    if ! grep -q "$entry" /etc/hosts; then
        echo "$entry" | sudo tee -a /etc/hosts
    fi
done

echo "已成功屏蔽官方域名通信！"

# 下载对应架构程序包

cd edge-node
rm -rf edge-node-linux-amd64-plus-v1.4.7.zip
if [[ "$cpu_arch" == "x86_64" ]]; then
    wget https://dl.naixi.net/cdn/goedge/1.4.7/edge-node-linux-amd64-plus-v1.4.7.zip
    echo "已下载X86架构的安装包"
elif [[ "$cpu_arch" == "aarch64" ]]; then
    wget https://dl.naixi.net/cdn/goedge/1.4.7/edge-node-linux-arm64-plus-v1.4.7.zip
    echo "已下载ARM架构的安装包"
else
    echo "不支持的CPU架构"
    exit 1
fi

# 停止node
edge-node/bin/edge-node stop
# 清理缓存
rm -rf edge-node/data
rm -rf edge-node/bin
rm -rf /opt/cache
# 解压缩程序包
unzip -o edge-node-linux-*.zip
edge-node restart
# 注册服务
edge-node/bin/edge-node service
# 流程执行完毕
clear
echo -e "Succ"