#!/bin/bash

# HubProxy 一键安装脚本
# 支持 Debian/Ubuntu/CentOS7
set -e

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

# 配置
REPO="sky22333/hubproxy"
GITHUB_API="https://api.github.com/repos/${REPO}"
GITHUB_RELEASES="${GITHUB_API}/releases"
SERVICE_NAME="hubproxy"
INSTALL_DIR="/opt/hubproxy"
CONFIG_FILE="config.toml"
BINARY_NAME="hubproxy"
LOG_DIR="/var/log/hubproxy"
TEMP_DIR="/tmp/hubproxy-install"

echo -e "${BLUE}HubProxy 一键安装脚本${NC}"
echo "================================================="

# 必须 root
if [[ $EUID -ne 0 ]]; then
    echo -e "${RED}此脚本需要root权限运行${NC}"
    echo "请使用: sudo $0"
    exit 1
fi

# 架构检测
detect_arch() {
    case $(uname -m) in
        x86_64) echo "amd64" ;;
        aarch64|arm64) echo "arm64" ;;
        *)
            echo -e "${RED}不支持的架构${NC}"
            exit 1
        ;;
    esac
}
ARCH=$(detect_arch)
echo -e "${BLUE}检测到架构: linux-${ARCH}${NC}"

# 系统检测
detect_os() {
    if [ -f /etc/redhat-release ]; then
        echo "centos"
    elif [ -f /etc/debian_version ]; then
        echo "debian"
    else
        echo -e "${RED}不支持的操作系统${NC}"
        exit 1
    fi
}
OS=$(detect_os)
echo -e "${BLUE}检测到系统: ${OS}${NC}"

# CentOS 版本校验
if [ "$OS" = "centos" ]; then
    CENTOS_VERSION=$(rpm -q --queryformat '%{VERSION}' centos-release 2>/dev/null || echo "unknown")
    if [[ "$CENTOS_VERSION" != "7" ]]; then
        echo -e "${RED}仅支持 CentOS 7${NC}"
        exit 1
    fi
fi

# 依赖安装函数
install_deps() {
    echo -e "${BLUE}检查依赖...${NC}"

    missing=()
    for cmd in curl jq tar; do
        if ! command -v $cmd &>/dev/null; then
            missing+=($cmd)
        fi
    done

    if [ ${#missing[@]} -eq 0 ]; then
        echo -e "${GREEN}依赖已满足${NC}"
        return
    fi

    echo -e "${YELLOW}安装依赖: ${missing[*]}${NC}"

    if [ "$OS" = "debian" ]; then
        apt update
        apt install -y curl jq tar
    elif [ "$OS" = "centos" ]; then
        yum install -y epel-release
        yum install -y curl jq tar
    fi
}

# 判断是否本地安装
if [ -f "${BINARY_NAME}" ]; then
    LOCAL_INSTALL=true
    echo -e "${BLUE}使用本地安装模式${NC}"
else
    LOCAL_INSTALL=false
    install_deps
fi

# 自动下载
if [ "$LOCAL_INSTALL" = false ]; then
    echo -e "${BLUE}获取最新版本...${NC}"
    LATEST_RELEASE=$(curl -s "${GITHUB_RELEASES}/latest")
    VERSION=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')

    if [ "$VERSION" = "null" ] || [ -z "$VERSION" ]; then
        echo -e "${RED}无法获取版本信息${NC}"
        exit 1
    fi

    echo -e "${GREEN}最新版本: ${VERSION}${NC}"

    ASSET_NAME="hubproxy-${VERSION}-linux-${ARCH}.tar.gz"
    DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${VERSION}/${ASSET_NAME}"

    rm -rf "${TEMP_DIR}"
    mkdir -p "${TEMP_DIR}"
    cd "${TEMP_DIR}"

    curl -L -o "${ASSET_NAME}" "${DOWNLOAD_URL}"
    tar -xzf "${ASSET_NAME}"
    cd hubproxy
fi

echo -e "${YELLOW}开始安装...${NC}"

# 停止旧服务
if systemctl is-active --quiet ${SERVICE_NAME}; then
    systemctl stop ${SERVICE_NAME}
fi

# 备份配置
CONFIG_BACKUP=false
if [ -f "${INSTALL_DIR}/${CONFIG_FILE}" ]; then
    cp "${INSTALL_DIR}/${CONFIG_FILE}" "${TEMP_DIR}/config.toml.backup"
    CONFIG_BACKUP=true
fi

# 创建目录
mkdir -p ${INSTALL_DIR}
mkdir -p ${LOG_DIR}
chmod 755 ${INSTALL_DIR}
chmod 755 ${LOG_DIR}

# 复制文件
cp "${BINARY_NAME}" "${INSTALL_DIR}/"
chmod +x "${INSTALL_DIR}/${BINARY_NAME}"

if [ -f "${CONFIG_FILE}" ] && [ "$CONFIG_BACKUP" = false ]; then
    cp "${CONFIG_FILE}" "${INSTALL_DIR}/"
fi

# 安装 systemd
cp "${SERVICE_NAME}.service" "/etc/systemd/system/"
systemctl daemon-reload

if [ "$CONFIG_BACKUP" = true ]; then
    cp "${TEMP_DIR}/config.toml.backup" "${INSTALL_DIR}/${CONFIG_FILE}"
fi

# SELinux 处理（CentOS7）
if [ "$OS" = "centos" ]; then
    if command -v getenforce &>/dev/null; then
        if [ "$(getenforce)" = "Enforcing" ]; then
            echo -e "${YELLOW}设置 SELinux 端口权限...${NC}"
            yum install -y policycoreutils-python >/dev/null 2>&1 || true
            semanage port -a -t http_port_t -p tcp 5000 2>/dev/null || true
        fi
    fi
fi

# firewalld 放行端口
if systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-port=5000/tcp
    firewall-cmd --reload
fi

# 启动服务
systemctl enable ${SERVICE_NAME}
systemctl start ${SERVICE_NAME}

sleep 2

if systemctl is-active --quiet ${SERVICE_NAME}; then
    echo ""
    echo -e "${GREEN}🎉 安装成功！${NC}"
    echo -e "${GREEN}运行端口: 5000${NC}"
    echo -e "${GREEN}配置文件: ${INSTALL_DIR}/${CONFIG_FILE}${NC}"
else
    echo -e "${RED}服务启动失败${NC}"
    journalctl -u ${SERVICE_NAME} -f
    exit 1
fi

# 清理
cd /
rm -rf "${TEMP_DIR}"
