#!/bin/bash
# GitLab社区版(CE)部署与卸载工具
# 适用系统: Ubuntu 20.04+/Debian 11+


# 颜色与样式定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # 重置颜色

# 图标定义
CHECK_MARK="${GREEN}✓${NC}"
INFO_MARK="${BLUE}ℹ${NC}"
WARNING_MARK="${YELLOW}⚠${NC}"
ERROR_MARK="${RED}✗${NC}"


# 安装GitLab函数
install_gitlab() {
    # 欢迎信息
    echo -e "\n${PURPLE}=============================================${NC}"
    echo -e "${PURPLE}          GitLab CE 自动部署工具             ${NC}"
    echo -e "${PURPLE}=============================================${NC}"
    echo -e "${INFO_MARK} 适用系统: Ubuntu 20.04+/Debian 11+"
    echo -e "${INFO_MARK} 开始安装流程，请稍候...\n"


    # 检查root权限
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "\n${ERROR_MARK} ${RED}错误: 请使用root权限运行脚本${NC}"
        exit 1
    fi


    # 自动获取本机IP（优先取第一个网卡IP）
    echo -e "\n${BLUE}----- 检测本机网络信息 -----${NC}"
    LOCAL_IP=$(hostname -I | awk '{print $1}')
    if [ -z "$LOCAL_IP" ]; then
        echo -e "${ERROR_MARK} ${RED}错误: 无法获取本机IP，请手动配置访问地址${NC}"
        exit 1
    fi
    echo -e "${CHECK_MARK} 成功获取本机IP: ${GREEN}$LOCAL_IP${NC}"


    # 核心配置参数
    GITLAB_EXTERNAL_URL="http://${LOCAL_IP}:81"
    PUMA_PORT="8081"
    PROMETHEUS_PORT="9096"
    GITLAB_VERSION="latest"

    # 显示配置信息
    echo -e "\n${BLUE}----- 部署配置信息 -----${NC}"
    echo -e "• 访问地址: ${GREEN}$GITLAB_EXTERNAL_URL${NC}"
    echo -e "• Puma端口: ${GREEN}$PUMA_PORT${NC}"
    echo -e "• Prometheus端口: ${GREEN}$PROMETHEUS_PORT${NC}"
    echo -e "• 安装版本: ${GREEN}$GITLAB_VERSION${NC}"


    # 步骤1: 系统准备
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤1/8: 系统准备              ${NC}"
    echo -e "${YELLOW}=============================================${NC}"

    # 配置时区（避免交互）
    echo -e "${WARNING_MARK} 配置时区（亚洲/上海）"
    debconf-set-selections <<< "tzdata tzdata/Areas select Asia"
    debconf-set-selections <<< "tzdata tzdata/Zones/Asia select Shanghai"

    # 更新包列表
    echo -e "${WARNING_MARK} 更新包列表（预估30秒-2分钟）"
    apt-get update -y >/dev/null || {
        echo -e "${ERROR_MARK} ${RED}包列表更新失败，请检查网络${NC}"
        exit 1
    }

    # 安装依赖
    echo -e "${WARNING_MARK} 安装必要依赖（预估1-3分钟）"
    DEBIAN_FRONTEND=noninteractive \
    apt-get install -y --no-install-recommends \
    curl openssh-server ca-certificates tzdata perl \
    >/dev/null 2>&1 || {
        echo -e "${ERROR_MARK} ${RED}依赖安装失败，请检查网络${NC}"
        exit 1
    }
    echo -e "${CHECK_MARK} 系统准备完成"


    # 步骤2: 安装邮件服务
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤2/8: 邮件服务              ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 安装Postfix邮件服务"
    debconf-set-selections <<< "postfix postfix/main_mailer_type select Internet Site"
    debconf-set-selections <<< "postfix postfix/mailname string $(hostname -f)"
    DEBIAN_FRONTEND=noninteractive apt-get install -y postfix >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} Postfix安装完成"
    else
        echo -e "${WARNING_MARK} ${YELLOW}邮件服务安装失败，不影响核心功能${NC}"
    fi


    # 步骤3: 添加GitLab仓库
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤3/8: 添加仓库              ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 配置官方软件源"
    curl -fsSL https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey | gpg --dearmor -o /usr/share/keyrings/gitlab-ce-archive-keyring.gpg >/dev/null 2>&1
    echo "deb [signed-by=/usr/share/keyrings/gitlab-ce-archive-keyring.gpg] https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/gitlab-ce.list >/dev/null

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} 仓库配置完成"
    else
        echo -e "${ERROR_MARK} ${RED}仓库配置失败，请检查网络${NC}"
        exit 1
    fi


    # 步骤4: 安装GitLab CE
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤4/8: 安装GitLab           ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${WARNING_MARK} 正在安装GitLab（预估5-15分钟）"
    apt-get update -y >/dev/null
    if [ "$GITLAB_VERSION" != "latest" ]; then
        DEBIAN_FRONTEND=noninteractive apt-get install -y gitlab-ce=$GITLAB_VERSION >/dev/null 2>&1
    else
        DEBIAN_FRONTEND=noninteractive apt-get install -y gitlab-ce >/dev/null 2>&1
    fi

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} GitLab安装完成"
    else
        echo -e "${ERROR_MARK} ${RED}GitLab安装失败${NC}"
        exit 1
    fi


    # 步骤5: 配置核心参数
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤5/8: 配置参数             ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 配置端口与访问地址"
    cat <<EOF >> /etc/gitlab/gitlab.rb
external_url '$GITLAB_EXTERNAL_URL'
nginx['listen_port'] = 81
puma['port'] = $PUMA_PORT
prometheus['listen_address'] = 'localhost:${PROMETHEUS_PORT}'
EOF

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} 参数配置完成"
    else
        echo -e "${ERROR_MARK} ${RED}配置文件写入失败${NC}"
        exit 1
    fi


    # 步骤6: 初始化配置
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤6/8: 初始化配置           ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${WARNING_MARK} 初始化配置（最耗时步骤，预估5-10分钟）"
    echo -e "${INFO_MARK} 请勿中断此过程"
    gitlab-ctl reconfigure >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} 配置初始化完成"
    else
        echo -e "${ERROR_MARK} ${RED}初始化失败${NC}"
        exit 1
    fi


    # 步骤7: 启动服务
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤7/8: 启动服务             ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 启动GitLab组件"
    gitlab-ctl start >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} 所有服务启动成功"
    else
        echo -e "${ERROR_MARK} ${RED}服务启动失败${NC}"
        exit 1
    fi


    # 步骤8: 防火墙配置
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤8/8: 防火墙配置           ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 配置防火墙规则"
    ufw allow ssh >/dev/null 2>&1
    ufw allow 81 >/dev/null 2>&1
    ufw --force enable >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo -e "${CHECK_MARK} 防火墙配置完成"
    else
        echo -e "${WARNING_MARK} ${YELLOW}防火墙配置失败${NC}"
    fi


    # 安装完成信息
    echo -e "\n${GREEN}=============================================${NC}"
    echo -e "${GREEN}              安装完成！������${NC}"
    echo -e "${GREEN}=============================================${NC}"
    echo -e "${INFO_MARK} 访问地址: ${GREEN}$GITLAB_EXTERNAL_URL${NC}"
    echo -e "${INFO_MARK} 初始账号: ${GREEN}root${NC}"
    
    if [ -f "/etc/gitlab/initial_root_password" ]; then
        INITIAL_PASSWORD=$(grep "Password:" /etc/gitlab/initial_root_password | awk '{print $NF}')
        echo -e "${INFO_MARK} 初始密码: ${GREEN}$INITIAL_PASSWORD${NC}"
        echo -e "${INFO_MARK} 密码有效期: 24小时（/etc/gitlab/initial_root_password）"
    else
        echo -e "${INFO_MARK} 初始密码: 请稍后查看 /etc/gitlab/initial_root_password"
    fi

    echo -e "\n${INFO_MARK} 常用命令:"
    echo -e "  • 重启服务: ${BLUE}gitlab-ctl restart${NC}"
    echo -e "  • 查看状态: ${BLUE}gitlab-ctl status${NC}"
    echo -e "\n${GREEN}=============================================${NC}"
}


# 卸载GitLab函数（彻底清理）
uninstall_gitlab() {
    # 警告信息
    echo -e "\n${RED}=============================================${NC}"
    echo -e "${RED}          警告：即将彻底卸载GitLab          ${NC}"
    echo -e "${RED}=============================================${NC}"
    echo -e "${WARNING_MARK} 此操作将删除所有GitLab数据、配置和依赖"
    echo -e "${WARNING_MARK} 包括仓库数据、数据库、日志和用户配置"
    echo -e "${WARNING_MARK} 操作不可逆，请确认是否继续 [y/N]?"
    read -p "请输入选择: " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo -e "\n${INFO_MARK} 卸载操作已取消${NC}"
        exit 0
    fi


    # 检查root权限
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "\n${ERROR_MARK} ${RED}错误: 请使用root权限运行卸载命令${NC}"
        exit 1
    fi


    # 步骤1: 停止服务
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤1/5: 停止服务             ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    if command -v gitlab-ctl &> /dev/null; then
        echo -e "${INFO_MARK} 停止GitLab服务"
        gitlab-ctl stop >/dev/null 2>&1
        echo -e "${CHECK_MARK} 服务已停止"
    else
        echo -e "${WARNING_MARK} GitLab服务未运行或未安装"
    fi


    # 步骤2: 卸载软件包
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤2/5: 卸载软件包           ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 移除GitLab CE包（预估1-2分钟）"
    apt-get remove -y gitlab-ce >/dev/null 2>&1
    apt-get purge -y gitlab-ce >/dev/null 2>&1  # 彻底清除配置文件
    echo -e "${CHECK_MARK} 软件包卸载完成"


    # 步骤3: 删除残留文件
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤3/5: 清理残留文件         ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 删除数据和配置目录"
    rm -rf /etc/gitlab/        # 配置文件
    rm -rf /var/opt/gitlab/    # 数据目录（仓库、数据库等）
    rm -rf /var/log/gitlab/    # 日志文件
    rm -rf /opt/gitlab/        # 安装目录
    echo -e "${CHECK_MARK} 残留文件清理完成"


    # 步骤4: 清理仓库配置
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤4/5: 清理仓库配置         ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 移除GitLab软件源"
    rm -f /etc/apt/sources.list.d/gitlab-ce.list
    rm -f /usr/share/keyrings/gitlab-ce-archive-keyring.gpg
    apt-get update -y >/dev/null  # 更新源列表
    echo -e "${CHECK_MARK} 仓库配置清理完成"


    # 步骤5: 清理依赖（可选组件）
    echo -e "\n${YELLOW}=============================================${NC}"
    echo -e "${YELLOW}               步骤5/5: 清理依赖             ${NC}"
    echo -e "${YELLOW}=============================================${NC}"
    echo -e "${INFO_MARK} 移除未使用的依赖（预估1-3分钟）"
    apt-get autoremove -y >/dev/null 2>&1
    apt-get autoclean >/dev/null 2>&1
    echo -e "${CHECK_MARK} 依赖清理完成"


    # 卸载完成信息
    echo -e "\n${GREEN}=============================================${NC}"
    echo -e "${GREEN}              卸载完成！${NC}"
    echo -e "${GREEN}=============================================${NC}"
    echo -e "${INFO_MARK} GitLab已彻底卸载，所有数据已清除"
    echo -e "${INFO_MARK} 如需重新安装，执行命令:"
    echo -e "  ${BLUE}cd /opt/ && wget -qO- http://116.205.97.109/scripts/gitlab.sh | bash -s -- --install${NC}"
    echo -e "\n${GREEN}=============================================${NC}"
}


# 主逻辑：解析参数
case "$1" in
    --install)
        install_gitlab
        ;;
    --uninstall)
        uninstall_gitlab
        ;;
    *)
        echo -e "${ERROR_MARK} ${RED}无效参数！请使用 --install 或 --uninstall${NC}"
        exit 1
        ;;
esac
