#!/bin/bash

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

# 代理配置
PROXY_URL="vless://30229969-1519-436e-9241-a8ef433ded01@172.98.22.69:443?type=tcp&encryption=none&security=reality&pbk=auuE2QmWskEyhrTsO307CpLzrJAaDvPaDYrmyiu1ehA&fp=chrome&sni=30229969.com&sid=8b&spx=%2F#proxy"

# GitHub相关配置
GITHUB_MIRRORS=(
    "https://hub.fastgit.xyz"
    "https://github.com.cnpmjs.org"
    "https://ghproxy.com"
    "https://gitclone.com"
    "https://gh.api.99988866.xyz"
)

# 检查系统
check_system() {
    if [ -f /etc/redhat-release ]; then
        echo "centos"
    elif grep -q "Ubuntu" /etc/issue; then
        echo "ubuntu"
    elif grep -q "Debian" /etc/issue; then
        echo "debian"
    else
        echo "unknown"
    fi
}

# 安装基础工具
install_basic_tools() {
    echo -e "${GREEN}安装必要工具...${NC}"
    
    local system=$(check_system)
    
    case $system in
        "centos")
            yum install -y curl wget git jq unzip || {
                echo -e "${RED}安装工具失败，尝试使用阿里云镜像...${NC}"
                sed -e 's|^mirrorlist=|#mirrorlist=|g' \
                    -e 's|^#baseurl=http://mirror.centos.org|baseurl=https://mirrors.aliyun.com|g' \
                    -i.bak /etc/yum.repos.d/CentOS-*.repo
                yum clean all
                yum install -y curl wget git jq unzip
            }
            ;;
        "ubuntu"|"debian")
            apt update || {
                echo -e "${RED}更新软件源失败，尝试使用阿里云镜像...${NC}"
                sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
                sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list
                sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list
                apt update
            }
            apt install -y curl wget git jq unzip
            ;;
        *)
            echo -e "${RED}不支持的Linux发行版${NC}"
            exit 1
            ;;
    esac
}

# 下载并配置Xray
setup_xray() {
    echo -e "${GREEN}设置Xray代理...${NC}"
    
    # 创建目录
    mkdir -p /tmp/xray-proxy
    cd /tmp/xray-proxy
    
    # 下载Xray
    local arch=$(uname -m)
    local xray_url=""
    
    case $arch in
        "x86_64")
            xray_url="https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-64.zip"
            ;;
        "aarch64")
            xray_url="https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-arm64-v8a.zip"
            ;;
        "armv7l")
            xray_url="https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-arm32-v7a.zip"
            ;;
        *)
            echo -e "${RED}不支持的架构: $arch${NC}"
            return 1
            ;;
    esac
    
    # 尝试多种方式下载Xray
    echo "下载Xray核心..."
    if ! wget -O xray.zip $xray_url; then
        echo -e "${YELLOW}直接下载失败，尝试使用镜像...${NC}"
        for mirror in "${GITHUB_MIRRORS[@]}"; do
            echo "尝试镜像: $mirror"
            if wget -O xray.zip "$mirror/$xray_url"; then
                echo -e "${GREEN}使用镜像下载成功${NC}"
                break
            fi
        done
    fi
    
    if [ ! -f "xray.zip" ]; then
        echo -e "${RED}Xray下载失败${NC}"
        return 1
    fi
    
    # 解压
    unzip -o xray.zip xray
    rm xray.zip
    chmod +x xray
    
    # 生成配置文件
    cat > config.json << 'EOF'
{
    "inbounds": [
        {
            "port": 10808,
            "protocol": "socks",
            "settings": {
                "auth": "noauth",
                "udp": true
            },
            "tag": "socks-in"
        },
        {
            "port": 10809,
            "protocol": "http",
            "settings": {
                "allowTransparent": false
            },
            "tag": "http-in"
        }
    ],
    "outbounds": [
        {
            "protocol": "vless",
            "settings": {
                "vnext": [
                    {
                        "address": "172.98.22.69",
                        "port": 443,
                        "users": [
                            {
                                "id": "30229969-1519-436e-9241-a8ef433ded01",
                                "encryption": "none",
                                "flow": ""
                            }
                        ]
                    }
                ]
            },
            "streamSettings": {
                "network": "tcp",
                "security": "reality",
                "realitySettings": {
                    "show": false,
                    "fingerprint": "chrome",
                    "serverName": "30229969.com",
                    "publicKey": "auuE2QmWskEyhrTsO307CpLzrJAaDvPaDYrmyiu1ehA",
                    "shortId": "8b",
                    "spiderX": "/"
                }
            },
            "tag": "proxy"
        }
    ]
}
EOF

    # 启动Xray
    ./xray run -config config.json &
    XRAY_PID=$!
    echo -e "${GREEN}Xray已启动 (PID: $XRAY_PID)${NC}"
    
    # 等待启动
    sleep 3
}

# 设置Git代理
setup_git_proxy() {
    echo -e "${GREEN}设置Git代理...${NC}"
    
    # 设置全局Git配置
    git config --global http.proxy "http://127.0.0.1:10809"
    git config --global https.proxy "http://127.0.0.1:10809"
    
    # 设置GitHub特定代理
    git config --global http.https://github.com.proxy "http://127.0.0.1:10809"
    
    echo -e "${GREEN}Git代理设置完成${NC}"
}

# 设置系统代理环境变量
setup_env_proxy() {
    echo -e "${GREEN}设置环境变量代理...${NC}"
    
    export http_proxy="http://127.0.0.1:10809"
    export https_proxy="http://127.0.0.1:10809"
    export HTTP_PROXY="http://127.0.0.1:10809"
    export HTTPS_PROXY="http://127.0.0.1:10809"
    export ALL_PROXY="http://127.0.0.1:10809"
    
    # 添加到bashrc（可选）
    cat >> ~/.bashrc << EOF

# Proxy settings for GitHub access
export http_proxy="http://127.0.0.1:10809"
export https_proxy="http://127.0.0.1:10809"
export HTTP_PROXY="http://127.0.0.1:10809"
export HTTPS_PROXY="http://127.0.0.1:10809"
export ALL_PROXY="http://127.0.0.1:10809"
EOF

    echo -e "${GREEN}环境变量设置完成${NC}"
}

# 测试GitHub连接
test_github_connection() {
    echo -e "${GREEN}测试GitHub连接...${NC}"
    
    echo -e "${BLUE}1. 测试直接连接:${NC}"
    timeout 10 curl -s https://api.github.com | grep -q "current_user_url" && echo -e "${GREEN}✓ 直接连接成功${NC}" || echo -e "${RED}✗ 直接连接失败${NC}"
    
    echo -e "${BLUE}2. 测试代理连接:${NC}"
    timeout 10 curl -s --proxy http://127.0.0.1:10809 https://api.github.com | grep -q "current_user_url" && echo -e "${GREEN}✓ 代理连接成功${NC}" || echo -e "${RED}✗ 代理连接失败${NC}"
    
    echo -e "${BLUE}3. 测试Git克隆:${NC}"
    timeout 30 git clone --depth=1 https://github.com/octocat/Hello-World.git /tmp/test-repo 2>/dev/null && {
        echo -e "${GREEN}✓ Git克隆成功${NC}"
        rm -rf /tmp/test-repo
    } || echo -e "${RED}✗ Git克隆失败${NC}"
}

# 配置APT/YUM使用代理（可选）
setup_package_manager_proxy() {
    echo -e "${GREEN}配置包管理器代理...${NC}"
    
    local system=$(check_system)
    
    case $system in
        "ubuntu"|"debian")
            # 配置APT代理
            cat > /etc/apt/apt.conf.d/95proxies << EOF
Acquire::http::proxy "http://127.0.0.1:10809/";
Acquire::https::proxy "http://127.0.0.1:10809/";
Acquire::ftp::proxy "http://127.0.0.1:10809/";
EOF
            echo -e "${GREEN}APT代理已配置${NC}"
            ;;
        "centos")
            # 配置YUM代理
            if [ -f /etc/yum.conf ]; then
                grep -q "proxy=" /etc/yum.conf || echo "proxy=http://127.0.0.1:10809" >> /etc/yum.conf
                echo -e "${GREEN}YUM代理已配置${NC}"
            fi
            ;;
    esac
}

# 下载GitHub资源（使用多种方式）
download_github_resource() {
    local url=$1
    local output=$2
    
    echo -e "${GREEN}下载GitHub资源: $url${NC}"
    
    # 方法1: 直接下载（使用代理）
    if wget --proxy=on -O "$output" "$url"; then
        echo -e "${GREEN}✓ 代理下载成功${NC}"
        return 0
    fi
    
    # 方法2: 使用镜像站
    for mirror in "${GITHUB_MIRRORS[@]}"; do
        local mirror_url="${url//https:\/\/github.com/$mirror}"
        echo "尝试镜像: $mirror_url"
        if wget -O "$output" "$mirror_url"; then
            echo -e "${GREEN}✓ 镜像下载成功${NC}"
            return 0
        fi
    done
    
    # 方法3: 使用ghproxy
    local ghproxy_url="https://ghproxy.com/$url"
    if wget -O "$output" "$ghproxy_url"; then
        echo -e "${GREEN}✓ ghproxy下载成功${NC}"
        return 0
    fi
    
    echo -e "${RED}✗ 所有下载方式都失败${NC}"
    return 1
}

# 清理函数
cleanup() {
    if [ ! -z "$XRAY_PID" ]; then
        kill $XRAY_PID 2>/dev/null
        echo -e "${GREEN}已停止代理服务${NC}"
    fi
    cd ~
}

# 显示使用说明
show_usage() {
    echo -e "${GREEN}=== 国内服务器GitHub访问工具 ===${NC}"
    echo
    echo -e "${BLUE}使用方法:${NC}"
    echo "  $0 [command]"
    echo
    echo -e "${BLUE}可用命令:${NC}"
    echo "  setup      - 完整设置代理环境"
    echo "  test       - 测试GitHub连接"
    echo "  download   - 下载GitHub资源"
    echo "  proxy-only - 仅启动代理服务"
    echo "  help       - 显示此帮助信息"
    echo
    echo -e "${BLUE}示例:${NC}"
    echo "  $0 setup                    # 完整设置"
    echo "  $0 download https://github.com/user/repo/archive/master.zip"
    echo
    echo -e "${BLUE}代理信息:${NC}"
    echo "  SOCKS5: 127.0.0.1:10808"
    echo "  HTTP:   127.0.0.1:10809"
    echo
}

# 主函数
main() {
    trap cleanup EXIT
    
    local command=${1:-"setup"}
    
    case $command in
        "setup")
            echo -e "${GREEN}开始完整设置...${NC}"
            install_basic_tools
            setup_xray
            setup_git_proxy
            setup_env_proxy
            setup_package_manager_proxy
            test_github_connection
            echo -e "${GREEN}设置完成！现在可以正常访问GitHub了${NC}"
            ;;
        "test")
            setup_xray
            test_github_connection
            ;;
        "download")
            if [ -z "$2" ]; then
                echo -e "${RED}请提供要下载的URL${NC}"
                exit 1
            fi
            setup_xray
            download_github_resource "$2" "${3:-downloaded-file}"
            ;;
        "proxy-only")
            setup_xray
            echo -e "${GREEN}代理服务已启动，按Ctrl+C停止${NC}"
            wait
            ;;
        "help"|*)
            show_usage
            ;;
    esac
}

# 运行主函数
main "$@"