#!/bin/bash

# 颜色
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}===== 步骤 1: 卸载旧版 certbot =====${NC}"
yum remove -y certbot python2-certbot* python3-certbot* certbot-nginx || true

echo -e "${GREEN}===== 步骤 2: 删除残留文件 =====${NC}"
rm -f /usr/bin/certbot /usr/local/bin/certbot
rm -f /bin/certbot

echo -e "${GREEN}===== 步骤 3: 安装 snapd =====${NC}"
yum install -y epel-release
yum install -y snapd

systemctl enable --now snapd.socket
ln -s /var/lib/snapd/snap /snap 2>/dev/null || true
echo -e "${YELLOW}等待 snapd 初始化...${NC}"
sleep 10
echo -e "${GREEN}===== 步骤 4: 安装最新 certbot =====${NC}"
snap install core; snap refresh core
snap install --classic certbot
ln -sf /snap/bin/certbot /usr/bin/certbot

echo -e "${GREEN}===== 步骤 5: 检查版本 =====${NC}"
certbot --version || { echo -e "${RED}certbot 安装失败！${NC}"; exit 1; }

echo -e "${GREEN}===== 步骤 6: 检查插件 =====${NC}"
certbot plugins

echo -e "${GREEN}>>> Certbot 已完成安装！你现在可以使用 certbot --nginx 申请证书了${NC}"
