#!/bin/bash

# VoceSpace 本地自动化部署脚本
# 支持一键部署 VoceSpace + LiveKit Server + Redis

set -e  # 遇到错误时退出

# 默认配置
CONFIG_FILE=""
HOST_IP=""
FORCE_REINSTALL=false
SKIP_REDIS=false
SKIP_LIVEKIT=false

# 显示使用帮助
show_help() {
    echo "=========================================="
    echo "VoceSpace 本地自动化部署脚本"
    echo "=========================================="
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --config FILE              指定 vocespace.conf.json 配置文件路径"
    echo "  --host-ip IP               指定宿主机IP地址"
    echo "  --force                    强制重新安装所有组件"
    echo "  --skip-redis               跳过 Redis 安装"
    echo "  --skip-livekit             跳过 LiveKit Server 安装"
    echo "  -h, --help                 显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 --config ./vocespace.conf.json"
    echo "  $0 --config ./config.json --host-ip 192.168.1.100"
    echo "  $0 --force --skip-redis"
    echo ""
    echo "默认配置文件格式:"
    echo '  {'
    echo '    "livekit": {'
    echo '      "key": "devkey",'
    echo '      "secret": "secret",'
    echo '      "url": "ws://YOUR_IP:7880"'
    echo '    },'
    echo '    "codec": "vp9",'
    echo '    "resolution": "1080p",'
    echo '    "redis": {'
    echo '      "enabled": true,'
    echo '      "host": "YOUR_IP",'
    echo '      "port": 6379,'
    echo '      "password": "vocespace"'
    echo '    }'
    echo '    "server_url": "localhost",'
    echo '    "host_token": "vocespace",'
    echo '    "license": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImhhbkBwcml2b2NlLmNvbSIsImV4cGlyZXNfYXQiOjE3NzkyNzg0MDAsImNyZWF0ZWRfYXQiOjE3NDc3NDI0MDAsImRvbWFpbnMiOiIqIiwibGltaXQiOiJwcm8iLCJpZCI6IjZkZjgyMTMyLTIyODQtNGY2MS1iYmZhLWZkZmU4YmMzMWE2NyJ9.PiagYRDWSpzhIdbnY-pp8QeOf5Ij7neV8RMEafDgVT4"'
    echo '  }'
    echo ""
}

# 解析命令行参数
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --config)
                CONFIG_FILE="$2"
                shift 2
                ;;
            --host-ip)
                HOST_IP="$2"
                shift 2
                ;;
            --force)
                FORCE_REINSTALL=true
                shift
                ;;
            --skip-redis)
                SKIP_REDIS=true
                shift
                ;;
            --skip-livekit)
                SKIP_LIVEKIT=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                echo "❌ 未知参数: $1"
                echo "使用 $0 --help 查看帮助信息"
                exit 1
                ;;
        esac
    done
}

# 检测操作系统和架构
detect_system() {
    OS=$(uname -s)
    ARCH=$(uname -m)
    
    echo "检测到系统: $OS"
    echo "检测到架构: $ARCH"
    
    case $ARCH in
        "x86_64"|"amd64")
            DOCKER_IMAGE="privoce/vocespace:latest"
            ;;
        "arm64"|"aarch64")
            DOCKER_IMAGE="privoce/vocespace:latest_arm"
            ;;
        *)
            echo "❌ 不支持的架构: $ARCH"
            exit 1
            ;;
    esac
    
    echo "将使用 Docker 镜像: $DOCKER_IMAGE"
}

# 自动检测宿主机IP
detect_host_ip() {
    if [[ -z "$HOST_IP" ]]; then
        echo "自动检测宿主机IP..."
        
        case $OS in
            "Darwin")  # macOS
                HOST_IP=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | head -1 | awk '{print $2}')
                ;;
            "Linux")
                HOST_IP=$(ip route get 8.8.8.8 | awk '{print $7; exit}' 2>/dev/null || hostname -I | awk '{print $1}')
                ;;
            *)
                echo "❌ 无法自动检测IP，请使用 --host-ip 参数指定"
                exit 1
                ;;
        esac
    fi
    
    if [[ -z "$HOST_IP" ]]; then
        echo "❌ 无法检测到宿主机IP，请使用 --host-ip 参数手动指定"
        exit 1
    fi
    
    echo "使用宿主机IP: $HOST_IP"
}

# 检查命令是否存在
check_command() {
    if command -v "$1" &> /dev/null; then
        echo "✅ $1 已安装"
        return 0
    else
        echo "❌ $1 未安装"
        return 1
    fi
}

# 检查 Docker 是否安装
check_docker() {
    echo "检查 Docker 安装状态..."
    if check_command docker; then
        echo "Docker 版本: $(docker --version)"
        
        # 检查 Docker 是否运行
        if ! docker info &> /dev/null; then
            echo "❌ Docker 未运行，请启动 Docker 服务"
            case $OS in
                "Darwin")
                    echo "请启动 Docker Desktop"
                    ;;
                "Linux")
                    echo "请运行: sudo systemctl start docker"
                    ;;
            esac
            exit 1
        fi
        return 0
    else
        echo "❌ Docker 未安装，请先安装 Docker"
        echo "安装指南: https://docs.docker.com/get-docker/"
        exit 1
    fi
}

# 创建默认配置文件
create_default_config() {
    local config_path="$1"
    
    cat > "$config_path" << EOF
{
  "livekit": {
    "key": "devkey",
    "secret": "secret",
    "url": "ws://${HOST_IP}:7880"
  },
  "codec": "vp9",
  "resolution": "1080p",
  "maxBitrate": 3000000,
  "maxFramerate": 30,
  "priority": "medium",
  "redis": {
    "enabled": true,
    "host": "${HOST_IP}",
    "port": 6379,
    "password": "vocespace",
    "db": 0
  },
  "server_url": "localhost",
  "host_token": "vocespace",
  "license": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImhhbkBwcml2b2NlLmNvbSIsImV4cGlyZXNfYXQiOjE3NzkyNzg0MDAsImNyZWF0ZWRfYXQiOjE3NDc3NDI0MDAsImRvbWFpbnMiOiIqIiwibGltaXQiOiJwcm8iLCJpZCI6IjZkZjgyMTMyLTIyODQtNGY2MS1iYmZhLWZkZmU4YmMzMWE2NyJ9.PiagYRDWSpzhIdbnY-pp8QeOf5Ij7neV8RMEafDgVT4"
}
EOF
    
    echo "✅ 已创建默认配置文件: $config_path"
}

# 验证和处理配置文件
handle_config_file() {
    if [[ -z "$CONFIG_FILE" ]]; then
        CONFIG_FILE="./vocespace.conf.json"
        echo "未指定配置文件，将创建默认配置: $CONFIG_FILE"
        create_default_config "$CONFIG_FILE"
    elif [[ ! -f "$CONFIG_FILE" ]]; then
        echo "❌ 配置文件不存在: $CONFIG_FILE"
        read -p "是否创建默认配置文件？(y/n): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            create_default_config "$CONFIG_FILE"
        else
            exit 1
        fi
    else
        echo "✅ 使用配置文件: $CONFIG_FILE"
        
        # 验证JSON格式
        if ! python3 -m json.tool "$CONFIG_FILE" > /dev/null 2>&1; then
            echo "❌ 配置文件JSON格式错误: $CONFIG_FILE"
            exit 1
        fi
        
        # 更新配置文件中的IP地址
        if command -v jq &> /dev/null; then
            temp_config=$(mktemp)
            jq --arg ip "$HOST_IP" '
                .livekit.url = "ws://\($ip):7880" |
                .redis.host = $ip
            ' "$CONFIG_FILE" > "$temp_config"
            mv "$temp_config" "$CONFIG_FILE"
            echo "✅ 已更新配置文件中的IP地址为: $HOST_IP"
        else
            echo "⚠️  未安装jq，无法自动更新配置文件中的IP地址"
            echo "请手动将配置文件中的IP地址更新为: $HOST_IP"
        fi
    fi
    
    # 转换为绝对路径
    CONFIG_FILE=$(realpath "$CONFIG_FILE")
}

# 安装 LiveKit Server
install_livekit() {
    if [[ "$SKIP_LIVEKIT" == "true" ]]; then
        echo "跳过 LiveKit Server 安装"
        return 0
    fi
    
    echo "=========================================="
    echo "安装 LiveKit Server"
    echo "=========================================="
    
    if check_command livekit-server && [[ "$FORCE_REINSTALL" != "true" ]]; then
        echo "LiveKit Server 已安装，跳过安装"
        return 0
    fi
    
    case $OS in
        "Darwin")
            echo "在 macOS 上安装 LiveKit Server..."
            if check_command brew; then
                brew update && brew install livekit
            else
                echo "❌ Homebrew 未安装，请先安装 Homebrew"
                echo "/bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
                exit 1
            fi
            ;;
        "Linux")
            echo "在 Linux 上安装 LiveKit Server..."
            curl -sSL https://get.livekit.io | bash
            ;;
        *)
            echo "❌ 不支持的操作系统: $OS"
            exit 1
            ;;
    esac
    
    echo "✅ LiveKit Server 安装完成"
}

# 安装 Redis
install_redis() {
    if [[ "$SKIP_REDIS" == "true" ]]; then
        echo "跳过 Redis 安装"
        return 0
    fi
    
    echo "=========================================="
    echo "安装 Redis"
    echo "=========================================="
    
    if check_command redis-server && [[ "$FORCE_REINSTALL" != "true" ]]; then
        echo "Redis 已安装，跳过安装"
        return 0
    fi
    
    case $OS in
        "Darwin")
            echo "在 macOS 上安装 Redis..."
            if check_command brew; then
                brew install redis
            else
                echo "❌ Homebrew 未安装，请先安装 Homebrew"
                exit 1
            fi
            ;;
        "Linux")
            echo "在 Linux 上安装 Redis..."
            if command -v apt-get &> /dev/null; then
                sudo apt-get update
                sudo apt-get install -y redis-server
            elif command -v yum &> /dev/null; then
                sudo yum install -y redis
            elif command -v dnf &> /dev/null; then
                sudo dnf install -y redis
            else
                echo "❌ 不支持的包管理器，请手动安装 Redis"
                exit 1
            fi
            ;;
        *)
            echo "❌ 不支持的操作系统: $OS"
            exit 1
            ;;
    esac
    
    echo "✅ Redis 安装完成"
}

# 拉取 VoceSpace 镜像
pull_vocespace_image() {
    echo "=========================================="
    echo "拉取 VoceSpace Docker 镜像"
    echo "=========================================="
    
    echo "拉取镜像: $DOCKER_IMAGE"
    docker pull "$DOCKER_IMAGE"
    echo "✅ 镜像拉取完成"
}

# 启动 Redis 服务
start_redis() {
    if [[ "$SKIP_REDIS" == "true" ]]; then
        echo "跳过 Redis 启动"
        return 0
    fi
    
    echo "=========================================="
    echo "启动 Redis 服务"
    echo "=========================================="
    
    # 检查 Redis 是否已在运行
    if pgrep -f "redis-server" > /dev/null; then
        echo "⚠️  Redis 已在运行"
        if [[ "$FORCE_REINSTALL" == "true" ]]; then
            echo "强制重启 Redis..."
            pkill -f "redis-server" || true
            sleep 2
        else
            echo "保持现有 Redis 运行"
            return 0
        fi
    fi
    
    echo "启动 Redis 服务..."
    
    case $OS in
        "Darwin")
            # macOS 使用 brew services
            if command -v brew &> /dev/null; then
                brew services start redis
                # 等待服务启动
                sleep 3
                # 配置密码
                redis-cli config set requirepass vocespace
                redis-cli -a vocespace config set bind "0.0.0.0"
            else
                nohup redis-server --requirepass "vocespace" --bind "0.0.0.0" --protected-mode no > redis.log 2>&1 &
            fi
            ;;
        "Linux")
            # Linux 使用后台启动
            nohup redis-server --requirepass "vocespace" --bind "0.0.0.0" --protected-mode no > redis.log 2>&1 &
            ;;
    esac
    
    sleep 3
    
    # 验证 Redis 是否启动成功
    if redis-cli -a vocespace ping &> /dev/null; then
        echo "✅ Redis 启动成功"
    else
        echo "❌ Redis 启动失败"
        return 1
    fi
}

# 启动 LiveKit Server
start_livekit() {
    if [[ "$SKIP_LIVEKIT" == "true" ]]; then
        echo "跳过 LiveKit Server 启动"
        return 0
    fi
    
    echo "=========================================="
    echo "启动 LiveKit Server"
    echo "=========================================="
    
    # 检查是否已在运行
    if pgrep -f "livekit-server" > /dev/null; then
        echo "⚠️  LiveKit Server 已在运行"
        if [[ "$FORCE_REINSTALL" == "true" ]]; then
            echo "强制重启 LiveKit Server..."
            pkill -f "livekit-server" || true
            sleep 2
        else
            echo "保持现有 LiveKit Server 运行"
            return 0
        fi
    fi
    
    echo "启动 LiveKit Server..."
    nohup livekit-server --dev --bind 0.0.0.0 > livekit-server.log 2>&1 &
    
    sleep 3
    
    if pgrep -f "livekit-server" > /dev/null; then
        echo "✅ LiveKit Server 启动成功"
        echo "日志文件: $(pwd)/livekit-server.log"
    else
        echo "❌ LiveKit Server 启动失败"
        echo "请检查日志: $(pwd)/livekit-server.log"
        return 1
    fi
}

# 启动 VoceSpace 容器
start_vocespace() {
    echo "=========================================="
    echo "启动 VoceSpace 容器"
    echo "=========================================="
    
    local container_name="vocespace"
    
    # 检查容器是否已存在
    if docker ps -a --format "{{.Names}}" | grep -q "^$container_name$"; then
        echo "检测到已存在的容器: $container_name"
        if [[ "$FORCE_REINSTALL" == "true" ]]; then
            echo "强制重新创建容器..."
            docker stop "$container_name" 2>/dev/null || true
            docker rm "$container_name" 2>/dev/null || true
        else
            read -p "是否要停止并重新创建容器？(y/n): " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                docker stop "$container_name" 2>/dev/null || true
                docker rm "$container_name" 2>/dev/null || true
            else
                echo "取消操作"
                return 1
            fi
        fi
    fi
    
    echo "启动 VoceSpace 容器..."
    echo "使用配置文件: $CONFIG_FILE"
    
    docker run -d \
        -p 3000:3000 \
        -v "$CONFIG_FILE:/app/vocespace.conf.json" \
        --name "$container_name" \
        "$DOCKER_IMAGE"
    
    echo "✅ VoceSpace 容器启动成功"
    echo "容器名称: $container_name"
    echo "访问地址: http://$HOST_IP:3000"
}

# 显示部署状态
show_status() {
    echo "=========================================="
    echo "部署状态检查"
    echo "=========================================="
    
    echo "🐳 Docker 容器状态:"
    docker ps --filter "name=vocespace" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || echo "❌ VoceSpace 容器未运行"
    
    echo ""
    echo "🔴 Redis 状态:"
    if pgrep -f "redis-server" > /dev/null; then
        echo "✅ Redis 正在运行"
        if redis-cli -a vocespace ping &> /dev/null; then
            echo "✅ Redis 连接正常"
        else
            echo "⚠️  Redis 连接失败"
        fi
    else
        echo "❌ Redis 未运行"
    fi
    
    echo ""
    echo "📡 LiveKit Server 状态:"
    if pgrep -f "livekit-server" > /dev/null; then
        echo "✅ LiveKit Server 正在运行"
    else
        echo "❌ LiveKit Server 未运行"
    fi
    
    echo ""
    echo "=========================================="
    echo "访问信息"
    echo "=========================================="
    echo "🌐 VoceSpace 应用: http://$HOST_IP:3000"
    echo "📡 LiveKit Server: ws://$HOST_IP:7880"
    echo "🔴 Redis 服务: $HOST_IP:6379"
    echo ""
    echo "📋 日志查看命令:"
    echo "  VoceSpace 容器日志: docker logs vocespace"
    echo "  LiveKit Server 日志: tail -f livekit-server.log"
    echo "  Redis 日志: tail -f redis.log"
    echo ""
    echo "⏹️  停止服务命令:"
    echo "  停止 VoceSpace: docker stop vocespace"
    echo "  停止 LiveKit: pkill -f livekit-server"
    echo "  停止 Redis: pkill -f redis-server"
}

# 主函数
main() {
    echo "=========================================="
    echo "VoceSpace 本地自动化部署脚本"
    echo "=========================================="
    
    # 解析命令行参数
    parse_args "$@"
    
    echo "开始部署流程..."
    
    # 检测系统
    detect_system
    
    # 检测宿主机IP
    detect_host_ip
    
    # 处理配置文件
    handle_config_file
    
    echo ""
    echo "=========================================="
    echo "配置信息"
    echo "=========================================="
    echo "宿主机IP: $HOST_IP"
    echo "配置文件: $CONFIG_FILE"
    echo "Docker镜像: $DOCKER_IMAGE"
    echo "强制重装: $FORCE_REINSTALL"
    echo "跳过Redis: $SKIP_REDIS"
    echo "跳过LiveKit: $SKIP_LIVEKIT"
    echo ""
    
    # 检查Docker
    check_docker
    
    # 安装组件
    install_redis
    install_livekit
    
    # 拉取镜像
    pull_vocespace_image
    
    # 启动服务
    start_redis
    start_livekit
    start_vocespace
    
    echo ""
    echo "等待服务启动..."
    sleep 5
    
    # 显示状态
    show_status
    
    echo ""
    echo "=========================================="
    echo "🎉 部署完成！"
    echo "=========================================="
    echo "请在浏览器中访问: http://$HOST_IP:3000"
    echo ""
    echo "如遇到问题，请检查:"
    echo "1. 防火墙是否开放端口 3000, 6379, 7880"
    echo "2. 配置文件格式是否正确"
    echo "3. 各服务日志文件"
}

# 运行主函数
main "$@"
