#!/bin/bash

# ocloud-claw 一键安装脚本
# 包含 AWS CLI、MCP 服务和 Skill
# 用法: bash install.sh <AK> <SK>

set -e

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 自动检测是否在正确目录（解压到当前目录 vs 解压到子目录）
if [ -f "$SCRIPT_DIR/install.sh" ] && [ ! -d "$SCRIPT_DIR/aws-install" ]; then
    # 如果当前目录没有 aws-install，但上一级有，说明解压到了当前目录而非子目录
    if [ -f "$(dirname "$SCRIPT_DIR")/aws-install/awscliv2.zip" ]; then
        SCRIPT_DIR="$(dirname "$SCRIPT_DIR")"
    fi
fi

# 0. 检查 mcporter
echo -e "\n${GREEN}[0/6] 检查 mcporter...${NC}"
if ! command -v mcporter &> /dev/null; then
    echo "  mcporter 未安装，正在安装..."
    
    # 检查 npm
    if ! command -v npm &> /dev/null; then
        echo -e "  ${RED}npm 未安装，请先安装 Node.js${NC}"
        exit 1
    fi
    
    # 安装 mcporter
    npm install -g mcporter
    echo -e "  ${GREEN}mcporter 安装完成${NC}"
else
    echo -e "  ${GREEN}mcporter 已安装${NC}"
fi

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  ocloud-claw 一键安装脚本${NC}"
echo -e "${GREEN}========================================${NC}"

# 自动检测并切换到正确目录
if [ -f "$SCRIPT_DIR/install.sh" ] && [ ! -d "$SCRIPT_DIR/aws-install" ]; then
    if [ -f "$(dirname "$SCRIPT_DIR")/aws-install/awscliv2.zip" ]; then
        echo -e "${YELLOW}检测到文件解压到当前目录，切换到正确目录...${NC}"
        cd "$(dirname "$SCRIPT_DIR")"
        SCRIPT_DIR="$(pwd)"
    fi
fi

# 检查参数
if [ $# -lt 2 ]; then
    echo -e "${RED}用法: $0 <AK> <SK>${NC}"
    echo -e "${YELLOW}示例: $0 YourAccessKey YourSecretKey${NC}"
    exit 1
fi

AK="$1"
SK="$2"
ENDPOINT="https://fgws3-ocloud.ihep.ac.cn"

echo -e "\n${YELLOW}配置信息:${NC}"
echo "  AK: ${AK:0:10}..."
echo "  SK: ${SK:0:10}..."
echo "  ENDPOINT: $ENDPOINT"

# 1. 检查并安装 AWS CLI
echo -e "\n${GREEN}[1/6] 检查/安装 AWS CLI...${NC}"
if ! command -v aws &> /dev/null; then
    echo "  安装 AWS CLI..."
    cd /tmp
    
    # 检查是否已经有本地安装包
    if [ -f "$SCRIPT_DIR/aws-install/awscliv2.zip" ]; then
        echo "  使用本地安装包..."
        cp "$SCRIPT_DIR/aws-install/awscliv2.zip" /tmp/
        unzip -q -o awscliv2.zip
    else
        echo "  下载 AWS CLI..."
        curl -s "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o awscliv2.zip
        unzip -q awscliv2.zip
    fi
    
    # 安装到用户目录
    mkdir -p "$HOME/bin"
    ./aws/install -i "$HOME/aws-cli" -b "$HOME/bin"
    
    # 添加到 PATH
    if ! grep -q 'HOME/bin' "$HOME/.bashrc" 2>/dev/null; then
        echo 'export PATH="$HOME/bin:$PATH"' >> "$HOME/.bashrc"
    fi
    export PATH="$HOME/bin:$PATH"
    
    rm -rf awscliv2.zip aws
    echo -e "  ${GREEN}AWS CLI 安装完成 (到 $HOME/bin)${NC}"
else
    echo -e "  ${GREEN}AWS CLI 已安装${NC}"
fi

# 确保 aws 在当前会话的 PATH 中
export PATH="$HOME/bin:$PATH"

# 2. 配置 AWS
echo -e "\n${GREEN}[2/6] 配置 AWS...${NC}"
mkdir -p ~/.aws
echo "[default]" > ~/.aws/credentials
echo "aws_access_key_id = $AK" >> ~/.aws/credentials
echo "aws_secret_access_key = $SK" >> ~/.aws/credentials

echo "[default]" > ~/.aws/config
echo "region = cn-north-1" >> ~/.aws/config
echo "endpoint_url = $ENDPOINT" >> ~/.aws/config
echo -e "  ${GREEN}AWS 配置完成${NC}"

# 3. 测试 S3 连接
echo -e "\n${GREEN}[3/6] 测试 S3 连接...${NC}"
BUCKETS=$(aws s3 ls 2>&1)
if [ $? -eq 0 ]; then
    echo -e "  ${GREEN}S3 连接成功!${NC}"
    echo "$BUCKETS"
else
    echo -e "  ${RED}S3 连接失败，请检查 AK/SK${NC}"
    exit 1
fi

# 4. 安装 MCP 服务
echo -e "\n${GREEN}[4/6] 安装 MCP 服务...${NC}"

USER_HOME=$(eval echo ~)
MCP_DIR="$USER_HOME/.openclaw/workspace/s3-mcp"
mkdir -p "$MCP_DIR"

if [ -f "$SCRIPT_DIR/server.js" ]; then
    cp "$SCRIPT_DIR/server.js" "$MCP_DIR/server.js"
    cp "$SCRIPT_DIR/package.json" "$MCP_DIR/package.json"
    
    # 安装 Node 依赖
    echo "  安装 Node 依赖..."
    cd "$MCP_DIR"
    npm install @modelcontextprotocol/sdk 2>/dev/null || npm install
    echo -e "  ${GREEN}MCP 服务安装完成${NC}"
else
    echo -e "  ${YELLOW}未找到 MCP 服务文件，跳过${NC}"
fi

# 5. 配置 mcporter
echo -e "\n${GREEN}[5/6] 配置 mcporter...${NC}"

MCPorTER_CONFIG="$USER_HOME/.mcporter/mcporter.json"
mkdir -p "$USER_HOME/.mcporter"

# 创建或更新配置
if [ -f "$MCPorTER_CONFIG" ]; then
    # 检查是否已有 ocloud 配置
    if grep -q '"ocloud"' "$MCPorTER_CONFIG"; then
        echo -e "  ${YELLOW}mcporter 已有 ocloud 配置，跳过${NC}"
    else
        # 读取现有配置，添加 ocloud
        python3 -c "
import json
import os

config_path = os.path.expanduser('~/.mcporter/mcporter.json')
try:
    with open(config_path, 'r') as f:
        config = json.load(f)
    
    if 'mcpServers' not in config:
        config['mcpServers'] = {}
    
    config['mcpServers']['ocloud'] = {
        'command': 'node',
        'args': ['$MCP_DIR/server.js']
    }
    
    with open(config_path, 'w') as f:
        json.dump(config, f, indent=2)
    print('ok')
except Exception as e:
    print(f'error: {e}')
"
        if [ $? -eq 0 ]; then
            echo -e "  ${GREEN}mcporter 配置更新完成${NC}"
        else
            echo -e "  ${YELLOW}配置更新失败，请手动添加${NC}"
        fi
    fi
else
    cat > "$MCPorTER_CONFIG" << EOF
{
  "mcpServers": {
    "ocloud": {
      "command": "node",
      "args": ["$MCP_DIR/server.js"]
    }
  }
}
EOF
    echo -e "  ${GREEN}mcporter 配置创建完成${NC}"
fi

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}  安装完成!${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "\n${YELLOW}下一步:${NC}"
echo "  1. 重启 OpenClaw: openclaw gateway restart"
echo "  2. 验证: mcporter call ocloud.s3_list_buckets"
