#!/bin/bash
# XNode 完全自动化安装脚本
# 支持通过环境变量配置所有参数，无需交互

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CERT_CONFIG_FILE="${SCRIPT_DIR}/cert-config.json"
ENV_FILE="${SCRIPT_DIR}/.env"

# 加载 .env 文件（如果存在）
if [ -f "$ENV_FILE" ]; then
    # 读取 .env 文件，忽略注释和空行
    while IFS= read -r line || [ -n "$line" ]; do
        # 跳过注释和空行
        [[ "$line" =~ ^[[:space:]]*# ]] && continue
        [[ -z "${line// }" ]] && continue
        
        # 解析 KEY=VALUE 格式
        if [[ "$line" =~ ^[[:space:]]*([^=]+)=(.*)$ ]]; then
            key="${BASH_REMATCH[1]}"
            value="${BASH_REMATCH[2]}"
            
            # 移除 key 和 value 两端的空格
            key=$(echo "$key" | xargs)
            value=$(echo "$value" | xargs)
            
            # 移除 value 的引号（如果存在）
            value="${value#\"}"
            value="${value%\"}"
            value="${value#\'}"
            value="${value%\'}"
            
            # 如果环境变量未设置，则设置它（.env 文件优先级低于已存在的环境变量）
            if [ -z "${!key}" ]; then
                export "$key=$value"
            fi
        fi
    done < "$ENV_FILE"
fi

show_usage() {
    echo -e "${BLUE}XNode 完全自动化安装脚本${NC}"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo -e "${BLUE}选项:${NC}"
    echo "  --config-file PATH     使用指定的配置文件（如果存在则跳过创建）"
    echo "  --skip-cert-setup      跳过证书配置"
    echo "  --skip-service-install 跳过服务安装"
    echo "  --apply-cert           配置证书后自动申请证书"
    echo "  --help, -h             显示帮助信息"
    echo ""
    echo -e "${BLUE}环境变量（服务配置）:${NC}"
    echo "  XNODE_BINARY_PATH      可执行文件安装路径（默认: /usr/local/bin/xnode）"
    echo "  XNODE_CONFIG_FILE      配置文件路径（默认: 脚本目录/config.json）"
    echo ""
    echo -e "${BLUE}环境变量（证书配置）:${NC}"
    echo "  CERT_EMAIL              Let's Encrypt 邮箱"
    echo "  CERT_DOMAINS            域名列表（格式: domain:provider，多个用空格分隔）"
    echo "  ALIYUN_KEY              阿里云 Access Key ID"
    echo "  ALIYUN_SECRET           阿里云 Access Key Secret"
    echo "  CF_TOKEN                Cloudflare API Token"
    echo "  CF_API_KEY             Cloudflare API Key"
    echo "  CF_API_EMAIL           Cloudflare Email"
    echo "  CERT_OUTPUT_DIR         证书输出目录（默认: 脚本目录/certs）"
    echo ""
    echo -e "${BLUE}示例:${NC}"
    echo "  export CERT_EMAIL='admin@example.com'"
    echo "  export CERT_DOMAINS='ssrline.vip:aliyun v2dot.online:cf'"
    echo "  export ALIYUN_KEY='xxx' ALIYUN_SECRET='xxx'"
    echo "  export CF_TOKEN='xxx'"
    echo "  sudo $0"
    echo ""
}

# 生成证书配置文件
generate_cert_config() {
    local DOMAIN_LIST="$1"
    
    if [ -z "$DOMAIN_LIST" ]; then
        return 1
    fi
    
    # 转换为数组
    DOMAINS_ARRAY=($DOMAIN_LIST)
    
    # 检查是否有阿里云域名
    HAS_ALIYUN=false
    HAS_CF=false
    
    for domain_provider in "${DOMAINS_ARRAY[@]}"; do
        provider=$(echo "$domain_provider" | cut -d':' -f2)
        case $provider in
            aliyun) HAS_ALIYUN=true ;;
            cf|cloudflare) HAS_CF=true ;;
        esac
    done
    
    # 检查凭证
    if [ "$HAS_ALIYUN" = true ]; then
        if [ -z "$ALIYUN_KEY" ] || [ -z "$ALIYUN_SECRET" ]; then
            echo -e "${RED}错误: 阿里云 API 凭证未指定${NC}"
            return 1
        fi
    fi
    
    if [ "$HAS_CF" = true ]; then
        if [ -z "$CF_TOKEN" ] && ([ -z "$CF_API_KEY" ] || [ -z "$CF_API_EMAIL" ]); then
            echo -e "${RED}错误: Cloudflare API 凭证未指定${NC}"
            return 1
        fi
    fi
    
    # 生成配置文件
    cat > "$CERT_CONFIG_FILE" << EOF
{
  "domains": [
$(for domain_provider in "${DOMAINS_ARRAY[@]}"; do
    echo "    \"$domain_provider\""
done | sed '$!s/$/,/')
  ],
  "providers": {
$(if [ "$HAS_ALIYUN" = true ]; then
    cat << ALIYUN_EOF
    "aliyun": {
      "type": "aliyun",
      "access_key_id": "${ALIYUN_KEY}",
      "access_key_secret": "${ALIYUN_SECRET}"
    }$(if [ "$HAS_CF" = true ]; then echo ","; fi)
ALIYUN_EOF
fi
$(if [ "$HAS_CF" = true ]; then
    if [ -n "$CF_TOKEN" ]; then
        cat << CF_TOKEN_EOF
    "cf": {
      "type": "cloudflare",
      "api_token": "${CF_TOKEN}",
      "api_key": "",
      "api_email": ""
    }
CF_TOKEN_EOF
    else
        cat << CF_KEY_EOF
    "cf": {
      "type": "cloudflare",
      "api_token": "",
      "api_key": "${CF_API_KEY}",
      "api_email": "${CF_API_EMAIL}"
    }
CF_KEY_EOF
    fi
fi)
  },
  "cert": {
    "output_dir": "${CERT_OUTPUT_DIR}",
    "key_length": "ec-256",
    "renew_days": 30,
    "email": "${CERT_EMAIL}"
  }
}
EOF
    
    echo -e "${GREEN}证书配置文件已生成: $CERT_CONFIG_FILE${NC}"
    return 0
}

SKIP_CERT_SETUP=false
SKIP_SERVICE_INSTALL=false
APPLY_CERT=false
CONFIG_FILE_PATH=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --config-file)
            CONFIG_FILE_PATH="$2"
            shift 2
            ;;
        --skip-cert-setup)
            SKIP_CERT_SETUP=true
            shift
            ;;
        --skip-service-install)
            SKIP_SERVICE_INSTALL=true
            shift
            ;;
        --apply-cert)
            APPLY_CERT=true
            shift
            ;;
        --help|-h)
            show_usage
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            show_usage
            exit 1
            ;;
    esac
done

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  XNode 完全自动化安装${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 1. 安装服务
if [ "$SKIP_SERVICE_INSTALL" = false ]; then
    echo -e "${YELLOW}[1/3] 安装服务...${NC}"
    if [ -n "$CONFIG_FILE_PATH" ]; then
        XNODE_CONFIG_FILE="$CONFIG_FILE_PATH" "${SCRIPT_DIR}/install-service.sh" --skip-config
    else
        "${SCRIPT_DIR}/install-service.sh" --skip-config
    fi
    echo ""
else
    echo -e "${YELLOW}[1/3] 跳过服务安装${NC}"
    echo ""
fi

# 2. 配置证书（如果提供了证书相关环境变量）
if [ "$SKIP_CERT_SETUP" = false ] && [ -n "$CERT_EMAIL" ] && [ -n "$CERT_DOMAINS" ]; then
    echo -e "${YELLOW}[2/3] 配置证书...${NC}"
    if generate_cert_config "$CERT_DOMAINS"; then
        echo -e "${GREEN}证书配置完成${NC}"
        echo ""
        
        # 3. 申请证书（如果指定了 --apply-cert）
        if [ "$APPLY_CERT" = true ]; then
            echo -e "${YELLOW}[3/3] 申请证书...${NC}"
            "${SCRIPT_DIR}/cert-manager.sh"
            echo ""
        else
            echo -e "${YELLOW}[3/3] 跳过证书申请${NC}"
            echo -e "${YELLOW}提示: 使用 --apply-cert 选项可自动申请证书${NC}"
            echo ""
        fi
    else
        echo -e "${RED}证书配置失败${NC}"
        echo ""
    fi
else
    echo -e "${YELLOW}[2/3] 跳过证书配置${NC}"
    if [ -z "$CERT_EMAIL" ] || [ -z "$CERT_DOMAINS" ]; then
        echo -e "${YELLOW}提示: 设置 CERT_EMAIL 和 CERT_DOMAINS 环境变量可自动配置证书${NC}"
    fi
    echo ""
    echo -e "${YELLOW}[3/3] 跳过证书申请${NC}"
    echo ""
fi

echo -e "${GREEN}安装完成！${NC}"
echo ""
    echo "下一步:"
if [ "$SKIP_SERVICE_INSTALL" = false ]; then
    CONFIG_FILE="${XNODE_CONFIG_FILE:-${SCRIPT_DIR}/config.json}"
    echo "1. 编辑配置文件: ${CONFIG_FILE}"
    echo "2. 启动服务: systemctl start xnode"
    echo "3. 查看状态: systemctl status xnode"
fi
if [ "$SKIP_CERT_SETUP" = false ] && [ -n "$CERT_EMAIL" ] && [ -n "$CERT_DOMAINS" ]; then
    if [ "$APPLY_CERT" = false ]; then
        echo "4. 申请证书: ${SCRIPT_DIR}/cert-manager.sh"
    fi
    echo "5. 安装自动续期: ${SCRIPT_DIR}/install-cron.sh --install"
fi
echo ""
