#!/bin/bash

################################################################################
# Ubuntu 22.04 环境初始化脚本
# 用途：安装开发测试环境所需的基础工具
# 系统要求：Ubuntu 22.04
# 使用方法：sudo ./init_environment.sh
################################################################################

set -e

echo "==================================="
echo "开始安装环境依赖..."
echo "==================================="

# 更新系统
echo "[1/4] 更新系统包列表..."
apt-get update -y

# 安装基础工具
echo "[2/4] 安装基础工具..."
apt-get install -y \
    vim \
    curl \
    wget \
    git \
    htop \
    tree \
    net-tools \
    dnsutils \
    iputils-ping \
    telnet \
    traceroute \
    lsof \
    unzip \
    zip \
    tar \
    jq \
    ca-certificates \
    gnupg \
    lsb-release \
    software-properties-common \
    apt-transport-https \
    build-essential \
    python3 \
    python3-pip \
    python3-venv \
    tmux \
    ncdu

# 安装 Docker
echo "[3/4] 安装 Docker..."

# 卸载旧版本
apt-get remove -y docker docker-engine docker.io containerd runc 2>/dev/null || true

# 添加 Docker 官方 GPG key
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

# 添加 Docker 仓库
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  tee /etc/apt/sources.list.d/docker.list > /dev/null

# 更新包列表并安装 Docker
apt-get update -y
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 启动 Docker 服务
systemctl start docker
systemctl enable docker

# 添加当前用户到 docker 组
if [ -n "$SUDO_USER" ]; then
    usermod -aG docker "$SUDO_USER"
    echo "✓ 用户 $SUDO_USER 已添加到 docker 组"
fi

# 清理
echo "[4/4] 清理..."
apt-get autoremove -y
apt-get autoclean -y

# 显示安装结果
echo ""
echo "==================================="
echo "安装完成！"
echo "==================================="
echo ""
echo "已安装："
echo "  ✓ vim"
echo "  ✓ curl, wget, git"
echo "  ✓ Docker: $(docker --version)"
echo "  ✓ Docker Compose: $(docker compose version)"
echo "  ✓ Python: $(python3 --version)"
echo "  ✓ 其他基础工具 (htop, tree, jq, tmux 等)"
echo ""
if [ -n "$SUDO_USER" ]; then
    echo "提示：请重新登录以使 docker 组权限生效"
fi
echo ""

