# +----------------------------------------------------------------------
# | Centos Stream 8 一键换yum源脚本 2024/07/30
# +----------------------------------------------------------------------
# | Copyright (c) 2020-2099 https://github.com/gacjie
# +----------------------------------------------------------------------
# | Gacjie Open Source Script
# +----------------------------------------------------------------------
# | Author: Gacjie <gacjie@hotmail.com>  Apache 2.0 License Code
# +----------------------------------------------------------------------
#!/bin/bash

# 检查是否为root用户
if [ "$(id -u)" -ne 0 ]; then
    echo "$(date +'%H:%M:%S') 请使用root用户运行此脚本"
    exit 1
fi

script_name="Centos Stream 8 一键换yum源脚本"
script_path=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")
project_url="https://down.baota.me/project/mirror_sources"
mirror_url="https://vault.centos.org"

echo "$(date +'%H:%M:%S') 欢迎使用 ${script_name}"

speed_test(){
    mirrors_list=(
        "https://mirrors.aliyun.com/centos-vault"
        "https://mirrors.163.com/centos-vault"
        "https://mirrors.cloud.tencent.com/centos-vault"
        "https://mirrors.huaweicloud.com/centos-vault"
        "https://mirrors.tuna.tsinghua.edu.cn/centos-vault"
        "https://mirrors.ustc.edu.cn/centos-vault"
        "https://vault.centos.org"
    )
    mirror_file="${script_path}/mirrors_list.txt"
    rm -rf "${mirror_file}"
    if [ -f /usr/bin/curl ];then 
        curl_speed_test
    else 
        wget_speed_test
    fi;
    sort -n -o ${mirror_file} ${mirror_file}
    local mirror_line=$(head -n 1 "${mirror_file}")
    local line_url=$(echo "$mirror_line" | awk -F_ '{print $2}')
    if [[ "${line_url}" == *"https://"* ]]; then
        mirror_url=${line_url}
    fi
    echo "$(date +'%H:%M:%S') 当前镜像站点 ${mirror_url}"
    
}

curl_speed_test(){
    echo "$(date +'%H:%M:%S') 正在对镜像源进行下载测速"
	for mirror in ${mirrors_list[@]}; do
        local rsp_url="${mirror}/8-stream/BaseOS/x86_64/os/Packages/bpftool-4.18.0-552.1.1.el8.x86_64.rpm"
        local rsp_file="$(mktemp)"
        local rsp=$(curl --insecure "$rsp_url" -o "$rsp_file" -s --max-time 10 -w "%{time_connect}_%{http_code}_%{time_total}")
        local code=$(echo "$rsp" | awk -F_ '{print $2}')
        if [ "$code" == "200" ]; then
            local total=$(echo "$rsp" | awk -F_ '{print $3}')
            echo "${total}_${mirror}" >> ${mirror_file}
        fi 
        rm -rf "$rsp_file"
	done
}

wget_speed_test(){
    echo "$(date +'%H:%M:%S') 正在对镜像源进行下载测速"
	for mirror in ${mirrors_list[@]}; do
        local rsp_url="${mirror}/8-stream/BaseOS/x86_64/os/Packages/bpftool-4.18.0-552.1.1.el8.x86_64.rpm"
        local rsp_file="$(mktemp)"
        local start_time=$(date +%s%3N)
        
        # 执行 wget 命令下载文件
        wget --no-check-certificate "$rsp_url" -O "$rsp_file" --quiet --timeout=10
        local code=$?
        
        local end_time=$(date +%s%3N)
        
        # 计算时间差，精确到毫秒
        local milliseconds=$(( end_time - start_time ))
        local total_time=$(awk "BEGIN {printf \"%.3f\", $milliseconds / 1000}")
        
        if [ $code -eq 0 ]; then
            echo "${total_time}_${mirror}" >> "${mirror_file}"
        fi
        rm -rf "$rsp_file"
	done
}

backup_config(){
    echo "$(date +'%H:%M:%S') 正在备份YUM源配置文件"
    mkdir -p "${script_path}/mirror_sources"
    cp -r "/etc/yum.repos.d/"* "${script_path}/mirror_sources/"
}

download(){
    local download_url="${1}"
    local download_path="${2}"
    if [ -f /usr/bin/curl ];then 
        local rsp=$(curl --insecure "${download_url}" -o "${download_path}" -s --max-time 10 -w "%{time_connect}_%{http_code}_%{time_total}")
        local code=$(echo "$rsp" | awk -F_ '{print $2}')
        if [ "$code" == "200" ]; then
            echo "$(date +'%H:%M:%S') 文件 ${download_path} 下载成功"
        else
            echo "$(date +'%H:%M:%S') 文件 ${download_path} 下载失败"
            rm -rf ${download_path}
        fi 
    else 
        wget --no-check-certificate "${download_url}" -O "${download_path}" --quiet --timeout=10;
        local code=$?
        if [ $code -eq 0 ]; then
            echo "$(date +'%H:%M:%S') 文件 ${download_path} 下载成功"
        else
            echo "$(date +'%H:%M:%S') 文件 ${download_path} 下载失败"
            rm -rf ${download_path}
        fi
    fi;
}

download_config(){
    echo "$(date +'%H:%M:%S') 正在下载配置文件模板"
    local download_url="${project_url}/config/CentOS-Stream-8-Base.repo"
    local download_path="${script_path}/CentOS-Stream-Base.repo"
    download "${download_url}" "${download_path}" 
}

set_source_config(){
    echo "$(date +'%H:%M:%S') 正在设置配置文件模板"
    local config_path="${script_path}/CentOS-Stream-Base.repo"
    if [ -f "${config_path}" ]; then
        rm -rf "/etc/yum.repos.d/"*
        sed -e "s#{{URL}}#${mirror_url}#g" "${config_path}" > "${config_path}.tmp"
        mv "${config_path}.tmp" "${config_path}"
        cp -r "${config_path}" "/etc/yum.repos.d/"
        yum clean all 
        yum makecache
    fi
}

install_gpg_key(){
    local download_url="https://www.centos.org/keys/RPM-GPG-KEY-CentOS-Official"
    local key_path="${script_path}/RPM-GPG-KEY-centosofficial"
    download "${download_url}" "${key_path}" 
    if [ -f "${key_path}" ]; then
        cp ${key_path} "/etc/pki/rpm-gpg/"
        rpm --import "/etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial"
    fi
}

remind(){
    echo "$(date +'%H:%M:%S') 为避免冲突，/etc/yum.repos.d/目录下的所有旧YUM源配置文件，会被清空，文件会备份在 ${script_path}/mirror_sources/ 目录下"
    echo "$(date +'%H:%M:%S') 如有问题请执行 cp -r ${script_path}/mirror_sources/* /etc/yum.repos.d/ 命令恢复"
    echo "$(date +'%H:%M:%S') 如果你需要恢复如epel等其他源，请自行从${script_path}/mirror_sources/ 手动恢复对应文件"
    echo "$(date +'%H:%M:%S') 执行yum -y update命令后，配置文件会被恢复到官方源，需要再次执行脚本修改源配置文件。"
    echo "$(date +'%H:%M:%S') 小广告：香港8C8G 仅需50元/月 弘速云(hosuyun.com)"
    echo "$(date +'%H:%M:%S') ${script_name} 执行完成，感谢您的使用。"
}

main(){
    arch=$(uname -m)
    # 检查系统架构是否支持
    if [ "$arch" == "x86_64" ]; then
        speed_test
        backup_config
        download_config
        set_source_config
        remind
    else
        echo "未知的系统架构: $arch  本脚本暂不支持"
         exit 1
    fi
}
main