#!/bin/bash
set -e

echo "📦 一键安装 Docker + Docker Compose + Portainer（支持 Alpine / Debian / CentOS）"
echo "======================================================================"
sleep 1

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then
    echo "❌ 请使用 root 用户运行本脚本。"
    exit 1
fi

# 检查磁盘空间
AVAILABLE=$(df / | tail -1 | awk '{print $4}')
if [ "$AVAILABLE" -lt 100000 ]; then
    echo "⚠️ 检测到磁盘空间可能不足（可用 < 100MB），请清理磁盘后再运行。"
    df -h /
    exit 1
fi

# 判断系统类型
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS_ID=$ID
    OS_NAME=$NAME
elif [ -f /etc/alpine-release ]; then
    OS_ID="alpine"
    OS_NAME="Alpine Linux"
else
    echo "❌ 无法识别系统，脚本终止。"
    exit 1
fi

ARCH=$(uname -m)

# 判断是否在中国网络环境
echo "🌐 正在检测网络环境..."
if curl -s --connect-timeout 3 https://www.google.com >/dev/null 2>&1; then
    IN_CHINA=false
    echo "✅ 检测结果：国外网络环境"
else
    IN_CHINA=true
    echo "🌏 检测结果：中国网络环境"
fi

# 安装必要依赖
echo "🔧 安装必要依赖..."
case "$OS_ID" in
    ubuntu|debian)
        apt update -y
        apt install -y curl gnupg ca-certificates lsb-release apt-transport-https software-properties-common
        ;;
    centos|rocky|almalinux|rhel)
        yum install -y curl gnupg2 ca-certificates lsb-release
        ;;
    alpine)
        apk update
        apk add curl bash ca-certificates wget gnupg lsb-release
        ;;
    *)
        echo "⚠️ 暂不支持此系统：$OS_NAME ($OS_ID)"
        exit 1
        ;;
esac

# =======================
# 1️⃣ 安装 Docker
# =======================
if command -v docker &>/dev/null; then
    echo "🟢 已检测到 Docker，跳过安装。"
else
    echo "📥 安装 Docker 中..."
    case "$OS_ID" in
        ubuntu|debian)
            if $IN_CHINA; then
                echo "📥 使用清华源安装 Docker..."
                curl -fsSL https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/${OS_ID}/gpg | gpg --dearmor -o /usr/share/keyrings/docker.gpg
                echo \
                  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/${OS_ID} \
                  $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
                apt update -y
                apt install -y docker-ce docker-ce-cli containerd.io
            else
                curl -fsSL https://get.docker.com | bash
            fi
            ;;
        centos|rocky|almalinux|rhel)
            if $IN_CHINA; then
                echo "📥 使用阿里源安装 Docker..."
                yum install -y yum-utils
                yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
                yum install -y docker-ce docker-ce-cli containerd.io
            else
                curl -fsSL https://get.docker.com | bash
            fi
            ;;
        alpine)
            echo "📦 使用 apk 安装 Docker..."
            apk add docker docker-cli containerd
            ;;
    esac
fi

# 配置 Docker 镜像加速（仅国内）
if $IN_CHINA; then
    echo "🚀 配置国内 Docker 镜像加速器..."
    mkdir -p /etc/docker
    cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://docker.fuckjd.de"
  ]
}
EOF
fi

# 启动 Docker 服务（不同系统差异化）
echo "🔧 启动 Docker 服务..."
if command -v systemctl >/dev/null 2>&1; then
    systemctl enable docker
    systemctl restart docker
elif command -v rc-update >/dev/null 2>&1; then
    rc-update add docker boot
    service docker restart
else
    nohup dockerd >/dev/null 2>&1 &
fi

# =======================
# 2️⃣ 安装 Docker Compose
# =======================
if command -v docker-compose &>/dev/null; then
    echo "🟢 已检测到 Docker Compose，跳过安装。"
else
    echo "📥 安装 Docker Compose..."
    COMPOSE_VERSION="2.38.2"
    case "$ARCH" in
        x86_64)
            COMPOSE_URL="https://sh.digac.icu/soft/docker-compose/${COMPOSE_VERSION}/docker-compose-linux-x86_64"
            ;;
        aarch64 | arm64)
            COMPOSE_URL="https://sh.digac.icu/soft/docker-compose/${COMPOSE_VERSION}/docker-compose-linux-aarch64"
            ;;
        *)
            echo "❌ 不支持的架构: $ARCH，无法安装 Docker Compose。"
            exit 1
            ;;
    esac

    curl -L "$COMPOSE_URL" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
    echo "✅ Docker Compose 安装完成：$(docker-compose --version)"
fi

# =======================
# 3️⃣ 可选安装 Portainer
# =======================
read -p "❓ 是否安装 Portainer 面板？[y/N]: " install_portainer
if [[ "$install_portainer" =~ ^[Yy]$ ]]; then
    echo "🚀 安装 Portainer 容器..."
    docker volume create portainer_data
    docker run -d \
        -p 9000:9000 \
        --name portainer \
        --restart=always \
        -v /var/run/docker.sock:/var/run/docker.sock \
        -v portainer_data:/data \
        portainer/portainer-ce:latest
    echo "✅ Portainer 启动成功，访问地址: http://<你的服务器IP>:9000"
else
    echo "⏭️ 已跳过 Portainer 安装。"
fi

# =======================
# 最终信息
# =======================
echo
echo "✅ Docker 版本: $(docker -v)"
[[ -x /usr/local/bin/docker-compose ]] && echo "✅ Docker Compose 版本: $(docker-compose --version)"
echo "🎉 安装流程完成！"
