#!/bin/bash
# XNode Service Installation Script for CentOS 7
# 完全自动化安装，支持命令行参数和环境变量

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Get script directory (absolute path)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
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

# Default values
BINARY_NAME="xnode"
BINARY_PATH="/usr/local/bin/${BINARY_NAME}"
SERVICE_FILE="xnode.service"
SERVICE_PATH="/etc/systemd/system/${SERVICE_FILE}"
CONFIG_DIR="${SCRIPT_DIR}"
CONFIG_FILE="${CONFIG_DIR}/config.json"

# Parse command line arguments
SKIP_CONFIG_CREATE=false
FORCE_INSTALL=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-config)
            SKIP_CONFIG_CREATE=true
            shift
            ;;
        --force)
            FORCE_INSTALL=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --skip-config    跳过创建默认配置文件（如果已存在）"
            echo "  --force          强制安装（覆盖现有文件）"
            echo "  --help, -h       显示帮助信息"
            echo ""
            echo "Environment variables:"
            echo "  XNODE_BINARY_PATH    可执行文件安装路径（默认: /usr/local/bin/xnode）"
            echo "  XNODE_CONFIG_FILE     配置文件路径（默认: 脚本目录/config.json）"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            exit 1
            ;;
    esac
done

# Override with environment variables if set
BINARY_PATH="${XNODE_BINARY_PATH:-$BINARY_PATH}"
CONFIG_FILE="${XNODE_CONFIG_FILE:-$CONFIG_FILE}"

echo -e "${GREEN}XNode Service Installation Script${NC}"
echo "=========================================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root${NC}"
    exit 1
fi

# Check if binary exists in current directory
if [ ! -f "${SCRIPT_DIR}/${BINARY_NAME}" ]; then
    echo -e "${RED}Error: ${BINARY_NAME} not found in ${SCRIPT_DIR}${NC}"
    exit 1
fi

# Copy binary
echo -e "${YELLOW}Installing binary...${NC}"
if [ "$FORCE_INSTALL" = true ] || [ ! -f "$BINARY_PATH" ]; then
    cp "${SCRIPT_DIR}/${BINARY_NAME}" "${BINARY_PATH}"
    chmod +x "${BINARY_PATH}"
    echo -e "${GREEN}Binary installed to ${BINARY_PATH}${NC}"
else
    echo -e "${YELLOW}Binary already exists, skipping...${NC}"
fi

# Copy service file and update config path and working directory
echo -e "${YELLOW}Installing service file...${NC}"
if [ -f "${SCRIPT_DIR}/${SERVICE_FILE}" ]; then
    # 创建服务文件，替换配置文件路径和工作目录
    # 使用绝对路径更可靠
    # 注意：替换顺序很重要，先替换具体的路径，再替换通用的模式
    # 使用 @ 作为分隔符，避免路径中的特殊字符问题
    sed -e "s@/usr/local/etc/xnode/config.json@${CONFIG_FILE}@g" \
        -e "s@-config [^ ]*@-config ${CONFIG_FILE}@g" \
        -e "s@WorkingDirectory=.*@WorkingDirectory=${CONFIG_DIR}@g" \
        -e "s@User=.*@User=$(whoami)@g" \
        "${SCRIPT_DIR}/${SERVICE_FILE}" > "${SERVICE_PATH}"
    chmod 644 "${SERVICE_PATH}"
    echo -e "${GREEN}Service file installed to ${SERVICE_PATH}${NC}"
    echo -e "${GREEN}Working directory: ${CONFIG_DIR}${NC}"
    echo -e "${GREEN}Config file path: ${CONFIG_FILE}${NC}"
else
    echo -e "${RED}Error: ${SERVICE_FILE} not found in ${SCRIPT_DIR}${NC}"
    exit 1
fi

# Create logs directory if it doesn't exist
LOGS_DIR="${CONFIG_DIR}/logs"
if [ ! -d "$LOGS_DIR" ]; then
    mkdir -p "$LOGS_DIR"
    chmod 755 "$LOGS_DIR"
    echo -e "${GREEN}Created logs directory: ${LOGS_DIR}${NC}"
fi

# Create config file if not exists and not skipped
if [ "$SKIP_CONFIG_CREATE" = false ] && [ ! -f "${CONFIG_FILE}" ]; then
    echo -e "${YELLOW}Creating default config file...${NC}"
    if [ -f "${SCRIPT_DIR}/config-template.json" ]; then
        cp "${SCRIPT_DIR}/config-template.json" "${CONFIG_FILE}"
        chmod 644 "${CONFIG_FILE}"
        echo -e "${GREEN}Config template copied to ${CONFIG_FILE}${NC}"
    else
        cat > "${CONFIG_FILE}" << 'EOF'
{
  "log": {
    "loglevel": "warning"
  },
  "inbounds": [],
  "outbounds": [
    {
      "protocol": "freedom",
      "settings": {}
    }
  ],
  "whmcs": {
    "enabled": true,
    "baseURL": "https://your-whmcs-domain.com/modules/addons/xray_admin/api.php",
    "token": "your-api-token-here",
    "pullInterval": "5m",
    "requestTimeout": "10s",
    "retry": {
      "count": 3,
      "backoff": "5s"
    },
    "nodes": [
      {
        "id": 1,
        "inboundTags": ["default"],
        "cleanup": true
      }
    ],
    "trafficReport": {
      "enabled": true,
      "interval": "10m"
    }
  }
}
EOF
        chmod 644 "${CONFIG_FILE}"
        echo -e "${GREEN}Default config file created at ${CONFIG_FILE}${NC}"
    fi
    echo -e "${YELLOW}Please edit ${CONFIG_FILE} with your actual configuration${NC}"
elif [ -f "${CONFIG_FILE}" ]; then
    echo -e "${GREEN}Config file already exists: ${CONFIG_FILE}${NC}"
fi

# Validate configuration file exists
if [ ! -f "${CONFIG_FILE}" ]; then
    echo -e "${RED}Error: Configuration file not found: ${CONFIG_FILE}${NC}"
    echo -e "${YELLOW}Please create the configuration file before starting the service${NC}"
    exit 1
fi

# Validate configuration file format (basic JSON check)
if command -v python3 &> /dev/null; then
    if ! python3 -m json.tool "${CONFIG_FILE}" > /dev/null 2>&1; then
        echo -e "${YELLOW}Warning: Configuration file may have JSON syntax errors${NC}"
        echo -e "${YELLOW}Please verify the JSON format: ${CONFIG_FILE}${NC}"
    fi
elif command -v python &> /dev/null; then
    if ! python -m json.tool "${CONFIG_FILE}" > /dev/null 2>&1; then
        echo -e "${YELLOW}Warning: Configuration file may have JSON syntax errors${NC}"
        echo -e "${YELLOW}Please verify the JSON format: ${CONFIG_FILE}${NC}"
    fi
fi

# Validate service file was created correctly
if [ ! -f "${SERVICE_PATH}" ]; then
    echo -e "${RED}Error: Service file was not created: ${SERVICE_PATH}${NC}"
    exit 1
fi

# Verify service file contains correct paths
if ! grep -q "WorkingDirectory=${CONFIG_DIR}" "${SERVICE_PATH}"; then
    echo -e "${YELLOW}Warning: WorkingDirectory may not be set correctly in service file${NC}"
fi

if ! grep -q "config ${CONFIG_FILE}" "${SERVICE_PATH}"; then
    echo -e "${YELLOW}Warning: Config path may not be set correctly in service file${NC}"
fi

# Reload systemd
echo -e "${YELLOW}Reloading systemd daemon...${NC}"
if ! systemctl daemon-reload; then
    echo -e "${RED}Error: Failed to reload systemd daemon${NC}"
    exit 1
fi

# Enable service
echo -e "${YELLOW}Enabling service...${NC}"
systemctl enable "${SERVICE_FILE}" 2>/dev/null || true

echo ""
echo -e "${GREEN}Installation completed!${NC}"
echo ""
echo "Configuration:"
echo "  Binary: ${BINARY_PATH}"
echo "  Config: ${CONFIG_FILE}"
echo "  Service: ${SERVICE_PATH}"
echo "  Working Directory: ${CONFIG_DIR}"
echo "  Logs Directory: ${LOGS_DIR}"
echo ""
echo "Next steps:"
echo "1. Edit configuration file if needed: ${CONFIG_FILE}"
echo "2. Test configuration: ${BINARY_PATH} run -config ${CONFIG_FILE} -test"
echo "3. Start the service: systemctl start xnode"
echo "4. Check status: systemctl status xnode"
echo "5. View logs: journalctl -u xnode -f"
echo "   Or: tail -f ${LOGS_DIR}/error.log"
echo ""
