#!/bin/bash

# 远程服务器安装脚本 - 安装 Docker 和必要的依赖
# 此脚本会在远程服务器上执行

set -e

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

echo -e "${GREEN}开始安装依赖...${NC}"

# 检测操作系统
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
else
    echo -e "${RED}无法检测操作系统${NC}"
    exit 1
fi

# 安装 Docker
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}安装 Docker...${NC}"
    
    # 使用官方安装脚本
    curl -fsSL https://get.docker.com | sh
    
    # 启动 Docker
    systemctl start docker || service docker start
    systemctl enable docker || true
    
    echo -e "${GREEN}✅ Docker 安装完成${NC}"
else
    echo -e "${GREEN}✅ Docker 已安装${NC}"
fi

# 安装 Docker Compose
if ! command -v docker-compose &> /dev/null; then
    echo -e "${YELLOW}安装 Docker Compose...${NC}"
    
    # 获取最新版本
    COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep -Po '"tag_name": "v\K[^"]*' || echo "2.23.0")
    
    # 下载 Docker Compose
    curl -L "https://github.com/docker/compose/releases/download/v${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    
    # 创建软链接
    ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose || true
    
    echo -e "${GREEN}✅ Docker Compose 安装完成${NC}"
else
    echo -e "${GREEN}✅ Docker Compose 已安装${NC}"
fi

# 配置防火墙（如果存在）
echo -e "${YELLOW}配置防火墙...${NC}"

# UFW (Ubuntu/Debian)
if command -v ufw &> /dev/null; then
    ufw allow 8080/tcp || true
    echo -e "${GREEN}✅ UFW 规则已添加${NC}"
fi

# FirewallD (CentOS/RHEL/Fedora)
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=8080/tcp || true
    firewall-cmd --reload || true
    echo -e "${GREEN}✅ FirewallD 规则已添加${NC}"
fi

# IPTables (通用)
if command -v iptables &> /dev/null && [ ! -f /.dockerenv ]; then
    iptables -I INPUT -p tcp --dport 8080 -j ACCEPT || true
    echo -e "${GREEN}✅ IPTables 规则已添加${NC}"
fi

# 创建 systemd 服务（可选）
if [ -d /etc/systemd/system ]; then
    echo -e "${YELLOW}创建 systemd 服务...${NC}"
    
    cat > /etc/systemd/system/proxy-server.service << EOF
[Unit]
Description=CodeLook Proxy Server
After=docker.service
Requires=docker.service

[Service]
Type=simple
WorkingDirectory=/opt/proxy-server
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    # 不自动启动，让用户选择是否使用 systemd
    # systemctl enable proxy-server
    
    echo -e "${GREEN}✅ Systemd 服务已创建（未启用）${NC}"
fi

# 优化系统设置
echo -e "${YELLOW}优化系统设置...${NC}"

# 增加文件描述符限制
if [ -f /etc/security/limits.conf ]; then
    grep -q "* soft nofile" /etc/security/limits.conf || echo "* soft nofile 65535" >> /etc/security/limits.conf
    grep -q "* hard nofile" /etc/security/limits.conf || echo "* hard nofile 65535" >> /etc/security/limits.conf
fi

# 优化网络参数
if [ -f /etc/sysctl.conf ]; then
    # 增加最大连接数
    grep -q "net.core.somaxconn" /etc/sysctl.conf || echo "net.core.somaxconn = 65535" >> /etc/sysctl.conf
    
    # 优化 TCP 参数
    grep -q "net.ipv4.tcp_tw_reuse" /etc/sysctl.conf || echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
    grep -q "net.ipv4.tcp_fin_timeout" /etc/sysctl.conf || echo "net.ipv4.tcp_fin_timeout = 30" >> /etc/sysctl.conf
    
    # 应用设置
    sysctl -p || true
fi

echo -e "${GREEN}✅ 系统优化完成${NC}"

# 显示版本信息
echo ""
echo -e "${GREEN}安装完成！版本信息：${NC}"
docker --version
docker-compose --version

echo ""
echo -e "${GREEN}✅ 所有依赖安装完成！${NC}"