#!/bin/bash
# CentOS Stream 8 一键配置阿里云镜像源脚本
# 功能：备份原有源，配置阿里云源，验证配置

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 检查是否为root用户
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}错误：此脚本需要root权限执行${NC}"
    exit 1
fi

# 1. 创建备份目录
echo -e "${YELLOW}➤ 创建备份目录...${NC}"
BACKUP_DIR="/etc/yum.repos.d/backup_$(date +%Y%m%d%H%M%S)"
mkdir -p "$BACKUP_DIR"
echo -e "${GREEN}✔ 备份目录创建成功: $BACKUP_DIR${NC}"

# 2. 备份原有repo文件
echo -e "${YELLOW}➤ 备份原有yum源配置...${NC}"
mv /etc/yum.repos.d/*.repo "$BACKUP_DIR" 2>/dev/null
echo -e "${GREEN}✔ 原有源已备份至: $BACKUP_DIR${NC}"
echo -e "备份的文件列表："
ls -l "$BACKUP_DIR"/

# 3. 配置阿里云镜像源
echo -e "${YELLOW}➤ 配置阿里云镜像源...${NC}"
cat > /etc/yum.repos.d/aliyun.repo <<EOF
[baseos]
name=CentOS Stream \$releasever - BaseOS - Aliyun
baseurl=https://mirrors.aliyun.com/centos/8-stream/BaseOS/\$basearch/os/
gpgcheck=0
enabled=1

[appstream]
name=CentOS Stream \$releasever - AppStream - Aliyun
baseurl=https://mirrors.aliyun.com/centos/8-stream/AppStream/\$basearch/os/
gpgcheck=0
enabled=1

[extras]
name=CentOS Stream \$releasever - Extras - Aliyun
baseurl=https://mirrors.aliyun.com/centos/8-stream/extras/\$basearch/os/
gpgcheck=0
enabled=1
EOF

echo -e "${GREEN}✔ 阿里云镜像源配置完成${NC}"
echo -e "配置内容："
cat /etc/yum.repos.d/aliyun.repo

# 4. 清理并重建缓存
echo -e "${YELLOW}➤ 清理并重建yum缓存...${NC}"
yum clean all
rm -rf /var/cache/yum
yum makecache

# 5. 验证配置
echo -e "\n${YELLOW}====== 验证配置 ======${NC}"
echo -e "${GREEN}✔ 当前生效的仓库列表：${NC}"
yum repolist

# 6. 测试安装
echo -e "\n${YELLOW}➤ 测试软件安装(vim)...${NC}"
if yum install -y vim; then
    echo -e "${GREEN}✔ vim安装成功${NC}"
else
    echo -e "${RED}✖ vim安装失败${NC}"
    echo -e "${YELLOW}尝试诊断问题...${NC}"
    yum check-update
    exit 1
fi

# 完成提示
echo -e "\n${GREEN}════════════════════════════════════════════════${NC}"
echo -e "${GREEN}           阿里云镜像源配置成功！               ${NC}"
echo -e "${GREEN}════════════════════════════════════════════════${NC}"
echo -e "操作总结："
echo -e "▪ 备份目录: ${YELLOW}$BACKUP_DIR${NC}"
echo -e "▪ 新配置文件: ${YELLOW}/etc/yum.repos.d/aliyun.repo${NC}"
echo -e "▪ 测试安装: ${GREEN}vim 安装成功${NC}"
echo -e "\n现在可以正常使用yum命令了，例如："
echo -e "  yum install <软件包名>"
echo -e "  yum update"