#!/bin/bash
set -Eeuo pipefail

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

# 打印带颜色的消息
print_message() {
    local color="$1"
    local message="$2"
    echo -e "${color}${message}${NC}"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" &>/dev/null
}

# 检测容器引擎
detect_container_engine() {
    if command_exists docker; then
        echo "docker"
    elif command_exists podman; then
        echo "podman"
    else
        echo "none"
    fi
}

# 获取用户安装路径
get_install_path() {
    echo >&2 
    print_message "$BLUE" "请输入Caddy安装路径 (留空则默认安装到 /opt/caddy):" >&2
    read -r -e -p "安装路径: " install_path
    
    if [ -z "$install_path" ]; then
        install_path="/opt/caddy"
    fi
    
    if [[ ! "$install_path" = /* ]]; then
        install_path="$(pwd)/$install_path"
    fi
    
    if command_exists realpath; then
        install_path="$(realpath -m "$install_path")"
    fi

    print_message "$BLUE" "将安装到: $install_path" >&2
    
    echo "$install_path" 
}

# Docker方式安装Caddy
install_caddy_docker() {
    print_message "$YELLOW" "使用Docker方式安装Caddy..."
    
    local CONTAINER_ENGINE
    CONTAINER_ENGINE=$(detect_container_engine)
    if [ "$CONTAINER_ENGINE" = "none" ]; then
        print_message "$RED" "未检测到Docker或Podman！"
        print_message "$YELLOW" "请先安装Docker或Podman后再运行此脚本。"
        print_message "$BLUE" "Docker安装命令: curl -fsSL https://get.docker.com | sh"
        exit 1
    fi
    print_message "$GREEN" "检测到容器引擎: $CONTAINER_ENGINE"
    
    local CADDY_DIR
    CADDY_DIR=$(get_install_path)
    
    print_message "$BLUE" "正在创建Caddy工作目录: ${CADDY_DIR}/caddy/"
    if ! mkdir -p "${CADDY_DIR}/caddy/"{sites,data,config,logs}; then
        print_message "$RED" "创建目录失败: ${CADDY_DIR}/caddy/"
        exit 1
    fi
    print_message "$GREEN" "目录结构创建完成: ${CADDY_DIR}/caddy/"
    
    print_message "$BLUE" "正在创建示例 index.html..."
    cat <<EOF > "${CADDY_DIR}/caddy/sites/index.html"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Caddy服务器 - 欢迎页面</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; color: white; }
        .container { text-align: center; padding: 2rem; background: rgba(255, 255, 255, 0.1); border-radius: 20px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.2); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); max-width: 600px; margin: 2rem; }
        .logo { font-size: 4rem; margin-bottom: 1rem; font-weight: bold; background: linear-gradient(45deg, #ff6b6b, #4ecdc4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
        h1 { font-size: 2.5rem; margin-bottom: 1rem; font-weight: 300; }
        .subtitle { font-size: 1.2rem; margin-bottom: 2rem; opacity: 0.9; }
        .features { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-top: 2rem; }
        .feature { padding: 1rem; background: rgba(255, 255, 255, 0.1); border-radius: 10px; border: 1px solid rgba(255, 255, 255, 0.1); }
        .feature-icon { font-size: 2rem; margin-bottom: 0.5rem; }
        .footer { margin-top: 2rem; opacity: 0.7; font-size: 0.9rem; }
        @media (max-width: 768px) { .logo { font-size: 3rem; } h1 { font-size: 2rem; } .subtitle { font-size: 1rem; } }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">🚀</div>
        <h1>Caddy服务器运行中</h1>
        <p class="subtitle">快速、安全、自动化的Web服务器</p>
        <div class="features">
            <div class="feature"><div class="feature-icon">🔒</div><h3>自动HTTPS</h3><p>自动获取和更新SSL证书</p></div>
            <div class="feature"><div class="feature-icon">⚡</div><h3>高性能</h3><p>HTTP/2和HTTP/3支持</p></div>
            <div class="feature"><div class="feature-icon">🔧</div><h3>易配置</h3><p>简洁的Caddyfile配置</p></div>
        </div>
        <div class="footer"><p>服务器时间: <span id="datetime"></span></p></div>
    </div>
    <script>
        function updateDateTime() { const now = new Date(); document.getElementById('datetime').textContent = now.toLocaleString('zh-CN'); }
        updateDateTime(); setInterval(updateDateTime, 1000);
    </script>
</body>
</html>
EOF
    
    print_message "$BLUE" "正在创建 Caddyfile..."
    cat <<EOF > "${CADDY_DIR}/caddy/Caddyfile"
{
  admin localhost:2019
  log {
      output file /var/log/caddy/access.log {
          roll_size 10mb
          roll_keep 5
          roll_keep_for 720h # 30 days
      }
      format json # For structured logging
      level INFO
  }
}

http://:80 {
    root * /srv
    file_server
    encode zstd gzip # Enable compression
}
EOF
    
    print_message "$BLUE" "正在创建 compose.yaml..."
    local compose_cmd_hint="$CONTAINER_ENGINE compose"
    if [ "$CONTAINER_ENGINE" = "podman" ] && ! command_exists podman-compose && ! (podman compose version &>/dev/null) ; then
        compose_cmd_hint="podman-compose (or ensure 'podman compose' is available)"
    fi

    cat <<EOF > "${CADDY_DIR}/compose.yaml"
services:
  caddy:
    image: caddy:latest
    container_name: caddy 
    restart: unless-stopped
    cap_add:
      - NET_ADMIN 
    network_mode: host 
    volumes:
      - ./caddy/Caddyfile:/etc/caddy/Caddyfile 
      - ./caddy/sites:/srv 
      - ./caddy/data:/data 
      - ./caddy/config:/config 
      - ./caddy/logs:/var/log/caddy 
    environment:
      - TZ=Asia/Shanghai 
    healthcheck:
      test: ["CMD", "caddy", "admin", "config", "dump", "--address", "localhost:2019"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 30s 
EOF
    
    print_message "$BLUE" "设置目录权限: ${CADDY_DIR}"
    chmod -R 755 "${CADDY_DIR}"
                                
    local caddy_helper_script_path="/root/.bash_caddy_helper"
    print_message "$BLUE" "正在创建 Caddy Helper 函数脚本: ${caddy_helper_script_path}"

cat <<EOF > "${caddy_helper_script_path}"
# Caddy Helper functions - Generated by Caddy installation script
# This script is intended to be sourced by your .bashrc or .zshrc.

# These variables are set at the time of script generation:
CADDY_HELPER_CADDY_DIR="${CADDY_DIR}"
CADDY_HELPER_CONTAINER_ENGINE="${CONTAINER_ENGINE}"
CADDY_HELPER_COMPOSE_CMD_HINT="${compose_cmd_hint}"
CADDY_HELPER_CADDYFILE_CONTAINER_PATH="/etc/caddy/Caddyfile" # Path inside the container
CADDY_HELPER_CADDYFILE_HOST_PATH="\$CADDY_HELPER_CADDY_DIR/caddy/Caddyfile" # Path on the host

# Color definitions for messages within the helper
CADDY_HELPER_RED='\033[0;31m'
CADDY_HELPER_GREEN='\033[0;32m'
CADDY_HELPER_YELLOW='\033[1;33m'
CADDY_HELPER_BLUE='\033[0;34m'
CADDY_HELPER_NC='\033[0m' # No Color

# print_message function local to this sourced script
_caddy_helper_print_message() {
    local color="\$1"
    local message="\$2"
    echo -e "\${color}\${message}\${CADDY_HELPER_NC}"
}

caddy_helper() {
    _ch_show_help() {
        _caddy_helper_print_message "\$CADDY_HELPER_BLUE" "Caddy Helper - Caddy容器管理工具 (sourced function)"
        echo
        echo "用法: caddy_helper <command>"
        echo
        _caddy_helper_print_message "\$CADDY_HELPER_YELLOW" "可用命令:"
        echo "  up        启动Caddy容器 (使用 '\$CADDY_HELPER_COMPOSE_CMD_HINT up -d')"
        echo "  down      停止Caddy容器 (使用 '\$CADDY_HELPER_COMPOSE_CMD_HINT down')"
        echo "  reload    格式化并重新加载Caddy配置 (在容器内执行)"
        echo "  edit      编辑宿主机上的Caddyfile (使用 \${EDITOR:-vim})"
        echo "  help      显示此帮助信息"
        echo
        _caddy_helper_print_message "\$CADDY_HELPER_BLUE" "相关路径和设置:"
        echo "  Caddy 安装目录 (宿主机): \$CADDY_HELPER_CADDY_DIR"
        echo "  Caddyfile (宿主机): \$CADDY_HELPER_CADDYFILE_HOST_PATH"
        echo "  使用的容器引擎命令: \$CADDY_HELPER_COMPOSE_CMD_HINT"
    }

    _ch_caddy_up() {
        _caddy_helper_print_message "\$CADDY_HELPER_YELLOW" "启动Caddy容器 (位于 \$CADDY_HELPER_CADDY_DIR)..."
        (cd "\$CADDY_HELPER_CADDY_DIR" && "\$CADDY_HELPER_CONTAINER_ENGINE" compose up -d)
        if [ \$? -eq 0 ]; then
            _caddy_helper_print_message "\$CADDY_HELPER_GREEN" "Caddy容器已启动或已在运行。 ✅"
        else
            _caddy_helper_print_message "\$CADDY_HELPER_RED" "启动Caddy容器失败。❌ 请检查 '\$CADDY_HELPER_CADDY_DIR/compose.yaml' 和相关日志。"
        fi
    }

    _ch_caddy_down() {
        _caddy_helper_print_message "\$CADDY_HELPER_YELLOW" "停止Caddy容器 (位于 \$CADDY_HELPER_CADDY_DIR)..."
        (cd "\$CADDY_HELPER_CADDY_DIR" && "\$CADDY_HELPER_CONTAINER_ENGINE" compose down)
        if [ \$? -eq 0 ]; then
            _caddy_helper_print_message "\$CADDY_HELPER_GREEN" "Caddy容器已停止。 ✅"
        else
            _caddy_helper_print_message "\$CADDY_HELPER_RED" "停止Caddy容器失败。❌"
        fi
    }
    
    _ch_caddy_reload() {
        _caddy_helper_print_message "\$CADDY_HELPER_YELLOW" "正在尝试格式化并重新加载Caddy配置..."
        _caddy_helper_print_message "\$CADDY_HELPER_BLUE"   "1. 在容器内格式化 Caddyfile: \$CADDY_HELPER_CADDYFILE_CONTAINER_PATH (这将修改宿主机上的文件)"
        "\$CADDY_HELPER_CONTAINER_ENGINE" exec caddy caddy fmt --overwrite "\$CADDY_HELPER_CADDYFILE_CONTAINER_PATH"
        local fmt_status=\$?
        if [ \$fmt_status -eq 0 ]; then
            _caddy_helper_print_message "\$CADDY_HELPER_GREEN" "Caddyfile 格式化成功 (或无需更改)。"
        else
            _caddy_helper_print_message "\$CADDY_HELPER_RED" "Caddyfile 格式化失败 (错误码: \$fmt_status)。 ❌ 请检查文件内容。"
            _caddy_helper_print_message "\$CADDY_HELPER_YELLOW" "仍然尝试重载配置..."
        fi
        
        _caddy_helper_print_message "\$CADDY_HELPER_BLUE" "2. 执行 reload 命令..."
        "\$CADDY_HELPER_CONTAINER_ENGINE" exec caddy caddy reload --config "\$CADDY_HELPER_CADDYFILE_CONTAINER_PATH" --adapter caddyfile
        if [ \$? -eq 0 ]; then
            _caddy_helper_print_message "\$CADDY_HELPER_GREEN" "Caddy配置已成功重新加载。✅"
        else
            _caddy_helper_print_message "\$CADDY_HELPER_RED" "重新加载Caddy配置失败. ❌ 请检查Caddy日志 (例如使用 '\$CADDY_HELPER_CONTAINER_ENGINE logs -f caddy') 和 Caddyfile ('caddy_helper edit')。"
        fi
    }

    _ch_caddy_edit() {
        _caddy_helper_print_message "\$CADDY_HELPER_YELLOW" "编辑Caddyfile配置 (宿主机路径: \$CADDY_HELPER_CADDYFILE_HOST_PATH)..."
        # shellcheck disable=SC2034 
        local editor_to_use="\${EDITOR:-vim}" 
        if ! command -v "\$(echo "\$editor_to_use" | cut -d' ' -f1)" &>/dev/null; then
             _caddy_helper_print_message "\$CADDY_HELPER_RED" "错误: 编辑器 '\$editor_to_use' 未找到. 请设置 EDITOR 环境变量或安装 vim."
             return 1
        fi
        "\$editor_to_use" "\$CADDY_HELPER_CADDYFILE_HOST_PATH"
        _caddy_helper_print_message "\$CADDY_HELPER_BLUE" "编辑完成后，记得运行 'caddy_helper reload' 来应用更改。💡"
    }

    if [ -z "\$1" ]; then
        _ch_show_help
        return 1 
    fi

    case "\$1" in
        up) _ch_caddy_up ;;
        down) _ch_caddy_down ;;
        reload) _ch_caddy_reload ;;
        edit) _ch_caddy_edit ;;
        help|--help|-h) _ch_show_help ;;
        *)
            _caddy_helper_print_message "\$CADDY_HELPER_RED" "错误: 未知命令 '\$1'"
            echo "使用 'caddy_helper help' 查看可用命令" >&2
            return 1
            ;;
    esac
    return 0 
}

# Bash Completion for caddy_helper function
_caddy_helper_completion_func() {
    local cur prev words cword opts
    if type _get_comp_words_by_ref &>/dev/null; then
        _get_comp_words_by_ref -n : cur prev words cword
    else
        cur="\${COMP_WORDS[COMP_CWORD]}"
        prev="\${COMP_WORDS[COMP_CWORD-1]}"
    fi
    
    opts="up down reload edit help"

    if [[ \${cur} == -* ]] ; then 
        COMPREPLY=( \$(compgen -W "--help -h" -- "\${cur}") )
        return 0
    fi

    COMPREPLY=( \$(compgen -W "\${opts}" -- "\${cur}") )
    return 0
}

if command -v complete &>/dev/null && command -v compgen &>/dev/null; then
    if ! complete -p | grep -q "_caddy_helper_completion_func caddy_helper"; then
        complete -F _caddy_helper_completion_func caddy_helper
    fi
fi
EOF

    local bashrc_file="/root/.bashrc"
    local source_marker="# Source Caddy Helper functions (managed by script)"
    local source_line="if [ -f \"${caddy_helper_script_path}\" ]; then . \"${caddy_helper_script_path}\"; fi"
    
    if ! grep -Fxq "${source_marker}" "${bashrc_file}"; then
        print_message "$BLUE" "添加 Caddy Helper 到 ${bashrc_file}"
        echo "" >> "${bashrc_file}" 
        echo "${source_marker}" >> "${bashrc_file}"
        echo "${source_line}" >> "${bashrc_file}"
        print_message "$GREEN" "Caddy Helper 已添加到 ${bashrc_file}。"
        print_message "$YELLOW" "请运行 'source ${bashrc_file}' 或重新登录以使用 'caddy_helper' 命令。"
    else
        print_message "$YELLOW" "Caddy Helper 的引入标记已存在于 ${bashrc_file}。如果脚本更新了，可能需要手动检查。"
    fi
    
    print_message "$GREEN" "Caddy Docker配置完成！ 🎉"
    print_message "$BLUE" "配置文件位置: ${CADDY_DIR}/caddy/Caddyfile"
    print_message "$BLUE" "网站文件目录: ${CADDY_DIR}/caddy/sites"
    print_message "$BLUE" "日志目录: ${CADDY_DIR}/caddy/logs"
    print_message "$BLUE" "Compose文件: ${CADDY_DIR}/compose.yaml"
    print_message "$YELLOW" "重要: 请运行 'source ${bashrc_file}' 或重新登录以激活 'caddy_helper' 命令。"
    print_message "$YELLOW" "然后使用 '${compose_cmd_hint} up -d' (或 'caddy_helper up') 启动容器。"
    print_message "$YELLOW" "使用 'caddy_helper help' 查看所有可用命令。"
}

install_caddy_traditional() {
    print_message "$YELLOW" "使用传统方式安装Caddy..."
    
    for cmd in curl jq wget tar mktemp; do 
        if ! command_exists "$cmd"; then
            print_message "$YELLOW" "正在安装依赖: $cmd..."
            # shellcheck disable=SC2015 # apt-get update can fail, but install might still work or be needed
            if command_exists apt-get; then
                apt-get update -y >/dev/null 2>&1 || true 
                apt-get install -y "$cmd"
            elif command_exists yum; then
                yum install -y "$cmd" 
            elif command_exists dnf; then
                dnf install -y "$cmd" 
            else
                print_message "$RED" "无法自动安装 $cmd。请手动安装后再试。"
                exit 1
            fi
        fi
    done
    
    local DOWNLOAD_DIR="" # Initialize to empty
    DOWNLOAD_DIR=$(mktemp -d -t caddy_download_XXXXXX)
    if [ -z "$DOWNLOAD_DIR" ] || [ ! -d "$DOWNLOAD_DIR" ]; then 
        print_message "$RED" "创建临时下载目录失败。"
        exit 1
    fi

    # Robust trap setting: Embed the actual path in the trap command.
    local cmd_to_trap_for_download_dir
    printf -v cmd_to_trap_for_download_dir 'if [ -d %q ]; then rm -rf -- %q; fi' "$DOWNLOAD_DIR" "$DOWNLOAD_DIR"
    trap "$cmd_to_trap_for_download_dir" EXIT SIGINT SIGTERM
    # This trap will be replaced if another function also sets a trap for these signals.
    # More advanced trap management would use a function to add/remove cleanup tasks.
    # For this script, this should be sufficient as only one temp dir is actively managed this way.

    cd "${DOWNLOAD_DIR}"
    
    print_message "$BLUE" "正在获取Caddy最新版本信息..."
    local CADDY_VERSION
    CADDY_VERSION=$(curl -s https://api.github.com/repos/caddyserver/caddy/releases/latest | jq -r '.tag_name')
    if [ -z "$CADDY_VERSION" ] || [ "$CADDY_VERSION" = "null" ] || [ "$CADDY_VERSION" = "" ]; then
        print_message "$RED" "无法获取Caddy最新版本号。请检查网络或GitHub API状态。"
        exit 1 # Trap will clean up DOWNLOAD_DIR
    fi
    CADDY_VERSION=${CADDY_VERSION#v} 
    print_message "$GREEN" "获取到Caddy最新版本: v${CADDY_VERSION}"
    
    print_message "$BLUE" "正在创建caddy用户和组 (如果不存在)..."
    if ! getent group caddy > /dev/null 2>&1; then
        groupadd --system caddy
    fi
    if ! getent passwd caddy > /dev/null 2>&1; then
        useradd --system --gid caddy --create-home --home-dir /var/lib/caddy \
                --shell /usr/sbin/nologin --comment "Caddy web server" caddy
    fi
    
    print_message "$BLUE" "正在下载Caddy v${CADDY_VERSION} for linux_amd64..."
    local caddy_archive="caddy_${CADDY_VERSION}_linux_amd64.tar.gz"
    wget --timeout=60 -q "https://github.com/caddyserver/caddy/releases/download/v${CADDY_VERSION}/${caddy_archive}"
    if [ ! -f "${caddy_archive}" ]; then
        print_message "$RED" "下载Caddy归档文件失败。"
        exit 1 # Trap will clean up
    fi

    print_message "$BLUE" "正在解压并安装Caddy..."
    tar -xzf "${caddy_archive}"
    mv caddy /usr/bin/
    chown root:root /usr/bin/caddy
    chmod 755 /usr/bin/caddy
    
    print_message "$BLUE" "正在下载并设置Caddy systemd服务文件..."
    wget --timeout=60 -q https://raw.githubusercontent.com/caddyserver/dist/master/init/caddy.service -O /etc/systemd/system/caddy.service
    
    print_message "$BLUE" "正在创建Caddy配置文件目录和示例文件..."
    mkdir -p /etc/caddy
    cat <<EOF > /etc/caddy/Caddyfile
{
  admin localhost:2019
  log {
      output file /var/log/caddy/access.log {
          roll_size 10mb
          roll_keep 5
          roll_keep_for 720h
      }
      format json
      level INFO
  }
}

http://:80 {
    root * /srv/www 
    file_server
    encode zstd gzip
}
EOF
    chown -R root:caddy /etc/caddy 
    chmod 750 /etc/caddy          
    chmod 640 /etc/caddy/Caddyfile 

    print_message "$BLUE" "正在创建网站根目录 /srv/www 和日志目录 /var/log/caddy..."
    mkdir -p /srv/www
    chown -R caddy:caddy /srv/www 
    chmod 755 /srv/www
    
    mkdir -p /var/log/caddy
    chown caddy:caddy /var/log/caddy
    chmod 750 /var/log/caddy

    if [ ! -f /srv/www/index.html ]; then
        print_message "$BLUE" "创建示例 /srv/www/index.html..."
        cat <<EOF > /srv/www/index.html
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>Caddy Works!</title></head>
<body style="font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 90vh; background-color: #f0f0f0;">
<div style="text-align: center; padding: 2em; background-color: white; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
<h1 style="color: #2c7EF9;">Caddy Server is Running!</h1>
<p>This is a site served by Caddy (traditional install).</p>
<p>Edit your Caddyfile at <code>/etc/caddy/Caddyfile</code>.</p>
<p>Your website root is <code>/srv/www</code>.</p>
</div></body></html>
EOF
        chown caddy:caddy /srv/www/index.html
        chmod 644 /srv/www/index.html
    fi
    
    print_message "$BLUE" "重新加载 systemd daemon并启动Caddy服务..."
    systemctl daemon-reload
    systemctl enable --now caddy
    
    print_message "$BLUE" "正在添加 caddy_edit 和 caddy_reload 别名到 .bashrc..."
    local CADDY_EDIT_ALIAS='alias caddy_edit="${EDITOR:-vim} /etc/caddy/Caddyfile"'
    local CADDY_RELOAD_ALIAS='alias caddy_reload="caddy fmt --overwrite /etc/caddy/Caddyfile && systemctl reload caddy"'
    
    local user_bashrc="<undefined>" 
    
    if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ] && [ -d "/home/${SUDO_USER}" ]; then # Avoid for 'sudo -u root' or if SUDO_USER is root
        user_bashrc="/home/${SUDO_USER}/.bashrc"
        # Check if .bashrc exists for SUDO_USER, if not, don't try to write
        if [ -f "$user_bashrc" ]; then
            if [ ! -w "$user_bashrc" ] && [ "$(stat -c '%U' "$user_bashrc")" = "$SUDO_USER" ]; then
                 print_message "$YELLOW" "警告: ${user_bashrc} 不可写，尝试使用 sudo -u ${SUDO_USER} tee 添加别名。"
                 {
                    echo "" 
                    echo "# Caddy aliases (traditional install - added by script)"
                    echo "$CADDY_EDIT_ALIAS"
                    echo "$CADDY_RELOAD_ALIAS"
                 } | sudo -u "${SUDO_USER}" tee -a "$user_bashrc" > /dev/null
            else # It's writable or not owned by SUDO_USER (edge case, proceed with current perms)
                print_message "$GREEN" "为用户 ${SUDO_USER} (${user_bashrc}) 添加别名..."
                if ! grep -Fxq "$CADDY_EDIT_ALIAS" "$user_bashrc"; then
                    echo -e "\n# Caddy aliases (traditional install)\n$CADDY_EDIT_ALIAS" >> "$user_bashrc"
                fi
                if ! grep -Fxq "$CADDY_RELOAD_ALIAS" "$user_bashrc"; then
                    echo "$CADDY_RELOAD_ALIAS" >> "$user_bashrc"
                fi
            fi
        else
            print_message "$YELLOW" ".bashrc 文件不存在: $user_bashrc (SUDO_USER case)。不添加别名。"
            user_bashrc="<不存在的 .bashrc for ${SUDO_USER}>"
        fi
    # Handles direct root execution or 'sudo su -', where $HOME is /root
    elif [ "$EUID" -eq 0 ] && [ -d "$HOME" ]; then 
        user_bashrc="${HOME}/.bashrc" 
        if [ -f "$user_bashrc" ]; then
            print_message "$GREEN" "为当前 root 用户 (${user_bashrc}) 添加别名..."
            if ! grep -Fxq "$CADDY_EDIT_ALIAS" "$user_bashrc"; then
                echo -e "\n# Caddy aliases (traditional install)\n$CADDY_EDIT_ALIAS" >> "$user_bashrc"
            fi
            if ! grep -Fxq "$CADDY_RELOAD_ALIAS" "$user_bashrc"; then
                echo "$CADDY_RELOAD_ALIAS" >> "$user_bashrc"
            fi
        else
             print_message "$YELLOW" ".bashrc 文件不存在: $user_bashrc (root case)。不添加别名。"
             user_bashrc="<不存在的 .bashrc for root>"
        fi
    else
        print_message "$YELLOW" "无法确定用户的 .bashrc 路径。不添加别名。"
        user_bashrc="<未找到的 .bashrc>"
    fi
    
    if [ -f "$user_bashrc" ] && [[ "$user_bashrc" != "<不存在"* ]] && [[ "$user_bashrc" != "<未找到"* ]]; then 
        print_message "$GREEN" "别名已添加/更新到 ${user_bashrc}。"
        print_message "$YELLOW" "请运行 'source ${user_bashrc}' 或重新登录以使用 'caddy_edit' 和 'caddy_reload' 别名。"
    fi

    cd "$HOME" 
    
    print_message "$GREEN" "Caddy v${CADDY_VERSION} 传统方式安装并启动成功！ ✨"
    print_message "$BLUE" "配置文件位置: /etc/caddy/Caddyfile"
    print_message "$BLUE" "网站根目录: /srv/www"
    print_message "$YELLOW" "检查服务状态: 'systemctl status caddy'"
    
    # Explicitly clear the trap for DOWNLOAD_DIR if function completes successfully.
    # This prevents the trap from attempting to remove a directory that was already handled
    # or if the script sets other traps later.
    # However, EXIT traps are tricky to "selectively" clear.
    # A common pattern is to let it fire and be idempotent (safe to run multiple times or on non-existent things).
    # The current trap is idempotent due to `if [ -d %q ]`.
    # To truly remove *this specific* trap, you'd need more complex trap management,
    # like `trap - EXIT SIGINT SIGTERM` which removes all traps for those signals.
    # For this script, relying on its idempotency is fine.
}

show_menu() {
    print_message "$BLUE"   "============================================"
    print_message "$BLUE"   "           Caddy 安装脚本 v1.6" 
    print_message "$BLUE"   "============================================"
    echo
    print_message "$YELLOW" "请选择安装方式:"
    echo "1) Docker方式安装 (推荐 ✨)"
    echo "2) 传统方式安装 (systemd服务)"
    echo "3) 退出"
    echo
}

main() {
    if [ "$EUID" -ne 0 ]; then
        print_message "$RED" "请使用sudo或root用户运行此脚本！"
        exit 1
    fi
    
    # Traps set inside functions are active for the current shell execution context.
    # If a function returns, the trap it set remains active for the script's lifetime
    # unless explicitly cleared or overridden.

    while true; do
        show_menu
        read -r -e -p "请输入选项 [1-3]: " choice
        
        case "$choice" in
            1)
                install_caddy_docker
                break
                ;;
            2)
                install_caddy_traditional
                break
                ;;
            3)
                print_message "$BLUE" "退出安装程序。拜拜~ 👋"
                # Any active EXIT trap (like the one for DOWNLOAD_DIR if traditional was started) will fire here.
                exit 0 
                ;;
            *)
                print_message "$RED" "无效选项，请输入1-3之间的数字。🤔"
                ;;
        esac
    done
    
    echo
    print_message "$GREEN" "============================================"
    print_message "$GREEN" "           Caddy 配置完成！"
    print_message "$GREEN" "============================================"
    print_message "$BLUE" "感谢使用此脚本！😊"
    # Script ends, any active EXIT trap will fire.
}

main "$@"

