#!/bin/bash
# 通用 OceanBase 仓库配置脚本
# 支持 EL7/EL8/EL9/Alinux，自动检测系统版本并配置对应的仓库和 GPG 密钥

set -e

echo "=========================================="
echo "通用 OceanBase 仓库配置"
echo "=========================================="
echo ""

# 检测系统信息
if [ -f /etc/os-release ]; then
    OS_ID=$(grep "^ID=" /etc/os-release | cut -d'=' -f2 | tr -d '"' | tr '[:upper:]' '[:lower:]')
    OS_VERSION=$(grep VERSION_ID /etc/os-release | cut -d'"' -f2 | cut -d'.' -f1)
    PRETTY_NAME=$(grep PRETTY_NAME /etc/os-release | cut -d'"' -f2)
    # 检测 PLATFORM_ID（用于 Alinux 版本映射）
    PLATFORM_ID=$(grep "^PLATFORM_ID=" /etc/os-release | cut -d'=' -f2 | tr -d '"' | tr '[:upper:]' '[:lower:]' || echo "")
else
    echo "❌ 无法检测系统版本"
    exit 1
fi

echo "系统信息:"
echo "  操作系统: $PRETTY_NAME"
echo "  OS ID: $OS_ID"
echo "  版本: $OS_VERSION"
[ -n "$PLATFORM_ID" ] && echo "  Platform ID: $PLATFORM_ID"
echo ""

# 判断系统类型并映射版本
if [[ "$OS_ID" == *"alinux"* ]] || [[ "$OS_ID" == *"alios"* ]]; then
    DISTRO_TYPE="alinux"
    DISTRO_NAME="Alinux"
    # Alinux 版本映射：Alinux 3 兼容 EL8
    if [ "$OS_VERSION" = "3" ]; then
        if [[ "$PLATFORM_ID" == *"al8"* ]]; then
            echo "  检测到 Alinux 3（兼容 EL8），映射到 EL8 配置"
            OS_VERSION="8"
        elif [[ "$PLATFORM_ID" == *"al7"* ]]; then
            echo "  检测到 Alinux 3（兼容 EL7），映射到 EL7 配置"
            OS_VERSION="7"
        else
            echo "  检测到 Alinux 3，默认映射到 EL8 配置"
            OS_VERSION="8"
        fi
    fi
elif [[ "$OS_ID" == *"centos"* ]] || [[ "$OS_ID" == *"rhel"* ]] || [[ "$OS_ID" == *"rocky"* ]] || [[ "$OS_ID" == *"almalinux"* ]]; then
    DISTRO_TYPE="el"
    DISTRO_NAME="EL"
else
    echo "⚠️  未知的系统类型: $OS_ID，默认使用 EL"
    DISTRO_TYPE="el"
    DISTRO_NAME="EL"
fi

echo "检测到的系统类型: $DISTRO_NAME$OS_VERSION（用于配置）"
echo ""

# 根据版本配置基础仓库（用于解决依赖）
case "$OS_VERSION" in
    7)
        echo "配置 EL7 基础仓库（使用阿里云镜像，用于解决依赖）..."
        
        cat > /etc/yum.repos.d/CentOS-Base.repo <<EOF
[base]
name=CentOS-\$releasever - Base - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
skip_if_unavailable=1

[updates]
name=CentOS-\$releasever - Updates - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/\$releasever/updates/\$basearch/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
skip_if_unavailable=1

[extras]
name=CentOS-\$releasever - Extras - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
skip_if_unavailable=1
EOF
        
        echo "  ✅ EL7 基础仓库配置完成"
        ;;
    8)
        echo "配置 EL8 基础仓库（使用阿里云镜像，用于解决依赖）..."
        
        # 检查本地 GPG 密钥文件是否存在，如果不存在则使用镜像站 URL
        if [ -f /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial ]; then
            GPG_KEY="file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial"
        else
            GPG_KEY="https://mirrors.aliyun.com/centos/RPM-GPG-KEY-centosofficial"
        fi
        
        cat > /etc/yum.repos.d/CentOS-Base.repo <<EOF
[baseos]
name=CentOS-\$releasever - BaseOS - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/\$releasever/BaseOS/\$basearch/os/
gpgcheck=1
enabled=1
gpgkey=$GPG_KEY
skip_if_unavailable=1

[appstream]
name=CentOS-\$releasever - AppStream - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/\$releasever/AppStream/\$basearch/os/
gpgcheck=1
enabled=1
gpgkey=$GPG_KEY
skip_if_unavailable=1

[extras]
name=CentOS-\$releasever - Extras - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/os/
gpgcheck=1
enabled=1
gpgkey=$GPG_KEY
skip_if_unavailable=1
EOF
        
        echo "  ✅ EL8 基础仓库配置完成"
        ;;
    9)
        echo "配置 EL9 基础仓库（使用阿里云镜像，用于解决依赖）..."
        
        # 检查本地 GPG 密钥文件是否存在，如果不存在则使用镜像站 URL
        if [ -f /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial ]; then
            GPG_KEY="file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial"
        else
            GPG_KEY="https://mirrors.aliyun.com/centos-stream/RPM-GPG-KEY-centosofficial"
        fi
        
        cat > /etc/yum.repos.d/CentOS-Base.repo <<EOF
[baseos]
name=CentOS-\$releasever - BaseOS - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-stream/\$releasever-stream/BaseOS/\$basearch/os/
gpgcheck=1
enabled=1
gpgkey=$GPG_KEY
skip_if_unavailable=1

[appstream]
name=CentOS-\$releasever - AppStream - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-stream/\$releasever-stream/AppStream/\$basearch/os/
gpgcheck=1
enabled=1
gpgkey=$GPG_KEY
skip_if_unavailable=1

[extras-common]
name=CentOS-\$releasever - Extras packages - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-stream/\$releasever-stream/extras/\$basearch/os/
gpgcheck=1
enabled=1
gpgkey=$GPG_KEY
skip_if_unavailable=1
EOF
        
        echo "  ✅ EL9 基础仓库配置完成"
        ;;
    *)
        echo "⚠️  未知的系统版本: $OS_VERSION"
        echo "   请手动配置仓库"
        exit 1
        ;;
esac

echo ""

# ==========================================
# 配置 OceanBase 仓库
# ==========================================
echo "配置 OceanBase 仓库..."

# EL7 使用主密钥，EL8/EL9 使用新密钥（支持子密钥）
if [ "$OS_VERSION" = "7" ]; then
    echo "  检测到 EL7，配置使用主密钥..."
    
    cat > /etc/yum.repos.d/OceanBase.repo <<EOF
# OceanBase.repo for EL7
# 使用主密钥，兼容 RPM 4.11.3

[oceanbase.community.stable.el7]
name=OceanBase-community-stable-el7
baseurl=https://mirrors.oceanbase.com/community/stable/el/7/\$basearch/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-el7
       https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-old
skip_if_unavailable=1
priority=1

[oceanbase.development-kit.el7]
name=OceanBase-development-kit-el7
baseurl=https://mirrors.oceanbase.com/development-kit/el/7/\$basearch/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-el7
       https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-old
skip_if_unavailable=1
priority=1
EOF
    
    # 导入 EL7 专用密钥
    echo "  导入 EL7 GPG 密钥..."
    rpm --import https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-el7 2>&1 | grep -v "already installed" || true
    rpm --import https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-old 2>&1 | grep -v "already installed" || true
    
else
    echo "  检测到 EL$OS_VERSION，配置使用新密钥（支持子密钥）..."
    
    cat > /etc/yum.repos.d/OceanBase.repo <<EOF
# OceanBase.repo for EL$OS_VERSION
# 使用新密钥，支持子密钥

[oceanbase.community.stable.el$OS_VERSION]
name=OceanBase-community-stable-el$OS_VERSION
baseurl=https://mirrors.oceanbase.com/community/stable/el/$OS_VERSION/\$basearch/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase
       https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-old
skip_if_unavailable=1
priority=1

[oceanbase.development-kit.el$OS_VERSION]
name=OceanBase-development-kit-el$OS_VERSION
baseurl=https://mirrors.oceanbase.com/development-kit/el/$OS_VERSION/\$basearch/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase
       https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-old
skip_if_unavailable=1
priority=1
EOF
    
    # 导入新密钥（包含主密钥和子密钥）
    echo "  导入 EL$OS_VERSION GPG 密钥（包含子密钥）..."
    
    # 先使用 GPG 导入（确保子密钥也被导入）
    TMP_KEY="/tmp/RPM-GPG-KEY-OceanBase-tmp"
    curl -s -f https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase > "$TMP_KEY" || {
        echo "  ⚠️  下载密钥失败，尝试直接导入..."
        rpm --import https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase 2>&1 | grep -v "already installed" || true
    }
    
    if [ -f "$TMP_KEY" ]; then
        # 使用 GPG 导入（会导入主密钥和子密钥）
        gpg --import "$TMP_KEY" 2>&1 | grep -E "imported|unchanged" || true
        
        # 然后导入到 RPM
        rpm --import "$TMP_KEY" 2>&1 | grep -v "already installed" || true
        
        rm -f "$TMP_KEY"
    fi
    
    # 导入旧密钥（兼容性）
    if [ "$OS_VERSION" = "8" ]; then
        rpm --import https://mirrors.oceanbase.com/RPM-GPG-KEY-OceanBase-old 2>&1 | grep -v "already installed" || true
    fi
fi

echo "  ✅ OceanBase 仓库配置完成"
echo ""

# ==========================================
# 清理缓存并验证
# ==========================================
echo "清理 YUM 缓存..."
yum clean all >/dev/null 2>&1 || true
echo "  ✅ 缓存已清理"
echo ""

# 验证配置
echo "验证配置..."
echo ""
echo "当前启用的仓库："
yum repolist enabled 2>/dev/null | head -15 || echo "  无法检测（可能需要 root 权限）"

echo ""
echo "验证 GPG 密钥..."
if [ "$OS_VERSION" = "7" ]; then
    rpm -qa | grep gpg-pubkey | grep -i "09e1cebf\|63476b06\|e9b4a7aa" | sed 's/^/  /' || echo "  未找到 EL7 密钥"
else
    rpm -qa | grep gpg-pubkey | grep -i "09e1cebf\|34a36966\|e9b4a7aa" | sed 's/^/  /' || echo "  未找到 EL$OS_VERSION 密钥"
fi

echo ""
echo "=========================================="
echo "配置完成"
echo "=========================================="
echo ""
echo "现在可以安装 OceanBase 包了："
echo "  yum install -y obclient"
echo "  yum install -y seekdb"
echo ""
echo "系统版本: $DISTRO_NAME$OS_VERSION"
echo "仓库类型: $DISTRO_TYPE"
echo ""
