#!/bin/bash
#====================================================================
# Description: CDN Installation Script / CDN 安装脚本
# Author: Liu YanHao
# Create Time: 2024-01-08
# Last Modified: 2025-01-09
# Version: 1.2
# Usage: ./cdn_install.sh <IP_ADDRESS> <SALT_ID_PREFIX>
# Example: ./cdn_install.sh 192.168.1.100 web
#====================================================================
set -e

function download_with_retry() {
    # Initialize variables for download retry / 初始化下载重试变量
    local url=$1
    local expected_md5=$2
    local retry_count=0
    local max_retries=3

    while [ $retry_count -lt $max_retries ]; do
        # Download file with curl or wget / 使用curl或wget下载文件
        { curl -o /root/cdninstall.tar.gz "$url" || wget -O /root/cdninstall.tar.gz "$url"; }

        # Check download status / 检查下载状态
        if [ ! -f /root/cdninstall.tar.gz ]; then
            retry_count=$((retry_count + 1))
            echo "下载失败，已重试 $retry_count 次（最多 $max_retries 次）"
            if [ $retry_count -eq $max_retries ]; then
                echo "达到最大重试次数，安装终止"
                exit 1
            fi
            sleep 3
            continue
        fi

        # Verify MD5 checksum / 验证MD5校验和
        CURRENT_MD5=$(md5sum /root/cdninstall.tar.gz | cut -d' ' -f1)

        if [ "$CURRENT_MD5" = "$expected_md5" ]; then
            echo "MD5校验成功"
            return 0
        else
            # Retry on MD5 mismatch / MD5不匹配时重试
            retry_count=$((retry_count + 1))
            echo "MD5校验失败，当前MD5: $CURRENT_MD5"
            echo "预期MD5: $expected_md5"
            if [ $retry_count -eq $max_retries ]; then
                echo "达到最大重试次数，安装终止"
                exit 1
            fi
            echo "已重试 $retry_count 次（最多 $max_retries 次）"
            rm -f /root/cdninstall.tar.gz
            sleep 3
        fi
    done
}

# Select installation package based on node type / 根据节点类型选择安装包
if [[ "${2}" == "test-node" ]]; then
    download_with_retry "http://deb.aorta.global/SuperCDN/cdninstall_test_v2.tar.gz" "832784ee740169f758d8a4ed281cc0cc"
else
    download_with_retry "http://deb.aorta.global/SuperCDN/cdninstall_prod_v2.tar.gz" "d794b819f5fefd6b56e5193bae95b6dc"
fi

# Extract and run installation / 解压并运行安装
tar -xzf /root/cdninstall.tar.gz && bash cdninstall/cdninstall.sh $1 $2

