#!/bin/bash

# 定义国内镜像源和官方源
MIRROR_CHINA="https://mirrors.aliyun.com/rockylinux"
MIRROR_OFFICIAL="https://dl.rockylinux.org/pub/rocky"

# 提示用户选择源
echo "请选择 Rocky Linux 的软件源："
echo "1. 国内镜像（阿里云）"
echo "2. 官方源"
read -p "请输入选项编号 (默认: 1): " SOURCE_CHOICE
SOURCE_CHOICE=${SOURCE_CHOICE:-1}

# 根据用户选择设置源
if [ "$SOURCE_CHOICE" = "1" ]; then
    MIRROR_URL="$MIRROR_CHINA"
    echo "已选择国内镜像源：$MIRROR_URL"
elif [ "$SOURCE_CHOICE" = "2" ]; then
    MIRROR_URL="$MIRROR_OFFICIAL"
    echo "已选择官方源：$MIRROR_URL"
else
    echo "无效选项，退出脚本。"
    exit 1
fi

# 备份原有的源配置文件
BACKUP_FILE="/etc/yum.repos.d/Rocky-BaseOS.repo.bak"
if [ ! -f "$BACKUP_FILE" ]; then
    sudo cp /etc/yum.repos.d/Rocky-BaseOS.repo "$BACKUP_FILE"
    echo "已备份原有源配置文件至：$BACKUP_FILE"
fi

# 替换源为选择的源
sudo sed -i "s|^mirrorlist=|#mirrorlist=|g" /etc/yum.repos.d/Rocky-*.repo
sudo sed -i "s|^#baseurl=http://dl.rockylinux.org/\$contentdir|baseurl=$MIRROR_URL|g" /etc/yum.repos.d/Rocky-*.repo

# 清理缓存并更新
echo "正在清理缓存并更新软件包列表..."
sudo yum clean all
sudo yum makecache

echo "软件源已成功修改为：$MIRROR_URL"
echo "你可以通过以下命令测试是否生效："
echo "  sudo yum update"