#!/bin/bash

# VoceSpace Automated Deployment Script
# Compatible with macOS and Linux systems

set -e  # Exit on error

# Default configuration
CONFIG_FILE=""
HOST_IP=""
FORCE_INSTALL=false
SKIP_REDIS=false
SKIP_LIVEKIT=false

# Show help information
show_help() {
    echo "=========================================="
    echo "VoceSpace Automated Deployment Script"
    echo "=========================================="
    echo ""
    echo "Usage: $0 [options]"
    echo ""
    echo "Options:"
    echo "  --config FILE              Specify configuration file path"
    echo "  --host-ip IP               Specify host machine IP address"
    echo "  --force                    Force reinstall all components"
    echo "  --skip-redis               Skip Redis installation"
    echo "  --skip-livekit             Skip LiveKit Server installation"
    echo "  -h, --help                 Show this help information"
    echo ""
    echo "Examples:"
    echo "  $0                                    # Basic deployment with default config"
    echo "  $0 --config ./config.json            # Use custom configuration file"
    echo "  $0 --host-ip 192.168.1.100           # Specify host IP"
    echo "  $0 --config ./config.json --force    # Force reinstall with custom config"
    echo "  $0 --skip-redis --skip-livekit       # Skip Redis and LiveKit installation"
    echo ""
}

# Parse command line arguments
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --config)
                CONFIG_FILE="$2"
                shift 2
                ;;
            --host-ip)
                HOST_IP="$2"
                shift 2
                ;;
            --force)
                FORCE_INSTALL=true
                shift
                ;;
            --skip-redis)
                SKIP_REDIS=true
                shift
                ;;
            --skip-livekit)
                SKIP_LIVEKIT=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                echo "❌ Unknown parameter: $1"
                echo "Use $0 --help to see help information"
                exit 1
                ;;
        esac
    done
}

echo "=========================================="
echo "VoceSpace Automated Deployment Script"
echo "=========================================="

# Detect operating system and architecture
OS=$(uname -s)
ARCH=$(uname -m)

echo "Detected system: $OS"
echo "Detected architecture: $ARCH"

# Function: Check if command exists
check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo "❌ $1 not installed"
        return 1
    else
        echo "✅ $1 is installed"
        return 0
    fi
}

# Function: Check Docker installation
check_docker() {
    if check_command docker; then
        echo "Docker version: $(docker --version)"
        # Check if Docker is running
        if ! docker info &> /dev/null; then
            echo "❌ Docker is not running, please start Docker service"
            case $OS in
                "Darwin")
                    echo "Please start Docker Desktop"
                    ;;
                "Linux")
                    echo "Run: sudo systemctl start docker"
                    ;;
            esac
            return 1
        fi
        echo "✅ Docker is running"
        return 0
    else
        echo "❌ Docker not installed, please install Docker first"
        echo "Please visit the following links to install Docker:"
        case $OS in
            "Darwin")
                echo "  macOS: https://docs.docker.com/desktop/install/mac-install/"
                ;;
            "Linux")
                echo "  Linux: https://docs.docker.com/engine/install/"
                ;;
            *)
                echo "  General: https://docs.docker.com/get-docker/"
                ;;
        esac
        return 1
    fi
}

# Function: Auto-detect host IP
detect_host_ip() {
    if [[ -n "$HOST_IP" ]]; then
        echo "Using specified host IP: $HOST_IP"
        return 0
    fi
    
    echo "Auto-detecting host IP address..."
    
    case $OS in
        "Darwin")
            # macOS
            HOST_IP=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | head -n1 | awk '{print $2}')
            ;;
        "Linux")
            # Linux
            HOST_IP=$(ip route get 8.8.8.8 | grep -oP 'src \K\S+' 2>/dev/null || \
                     hostname -I | awk '{print $1}' 2>/dev/null || \
                     ifconfig | grep "inet " | grep -v 127.0.0.1 | head -n1 | awk '{print $2}')
            ;;
    esac
    
    if [[ -z "$HOST_IP" ]]; then
        echo "❌ Unable to auto-detect host IP address"
        echo "Please specify manually using: --host-ip YOUR_IP"
        return 1
    fi
    
    echo "✅ Detected host IP: $HOST_IP"
    return 0
}

# Function: Create default configuration
create_default_config() {
    if [[ -z "$CONFIG_FILE" ]]; then
        CONFIG_FILE="./vocespace.conf.json"
        echo "Using default configuration file: $CONFIG_FILE"
    fi
    
    if [[ ! -f "$CONFIG_FILE" ]] || [[ "$FORCE_INSTALL" == true ]]; then
        echo "Creating default configuration file..."
        
        cat > "$CONFIG_FILE" << 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 "✅ Configuration file created: $CONFIG_FILE"
    else
        echo "✅ Using existing configuration file: $CONFIG_FILE"
        # Update IP addresses in existing configuration
        if command -v sed &> /dev/null; then
            sed -i.bak "s/YOUR_IP/$HOST_IP/g" "$CONFIG_FILE"
            echo "✅ Updated IP addresses in configuration file"
        fi
    fi
}

# Function: Install Redis
install_redis() {
    if [[ "$SKIP_REDIS" == true ]]; then
        echo "⏭️  Skipping Redis installation"
        return 0
    fi
    
    echo "=========================================="
    echo "Installing Redis"
    echo "=========================================="
    
    # Check if Redis is already running
    if pgrep -f "redis-server" > /dev/null && [[ "$FORCE_INSTALL" != true ]]; then
        echo "✅ Redis is already running"
        return 0
    fi
    
    case $OS in
        "Darwin")
            echo "Installing Redis on macOS..."
            if check_command brew; then
                brew install redis
                echo "Starting Redis..."
                brew services start redis
            else
                echo "❌ Homebrew not installed. Please install Homebrew first"
                echo "Homebrew installation: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
                return 1
            fi
            ;;
        "Linux")
            echo "Installing Redis on Linux..."
            if command -v apt-get &> /dev/null; then
                sudo apt-get update
                sudo apt-get install -y redis-server
                sudo systemctl start redis-server
                sudo systemctl enable redis-server
            elif command -v yum &> /dev/null; then
                sudo yum install -y redis
                sudo systemctl start redis
                sudo systemctl enable redis
            else
                echo "❌ Unsupported package manager"
                return 1
            fi
            ;;
        *)
            echo "❌ Unsupported operating system: $OS"
            return 1
            ;;
    esac
    
    # Configure Redis password
    echo "Configuring Redis password..."
    case $OS in
        "Darwin")
            REDIS_CONF="/usr/local/etc/redis.conf"
            ;;
        "Linux")
            REDIS_CONF="/etc/redis/redis.conf"
            ;;
    esac
    
    if [[ -f "$REDIS_CONF" ]]; then
        sudo sed -i.bak 's/# requirepass foobared/requirepass vocespace/' "$REDIS_CONF"
        case $OS in
            "Darwin")
                brew services restart redis
                ;;
            "Linux")
                sudo systemctl restart redis-server || sudo systemctl restart redis
                ;;
        esac
    fi
    
    echo "✅ Redis installation completed"
}

# Function: Install LiveKit Server
install_livekit() {
    if [[ "$SKIP_LIVEKIT" == true ]]; then
        echo "⏭️  Skipping LiveKit Server installation"
        return 0
    fi
    
    echo "=========================================="
    echo "Installing LiveKit Server"
    echo "=========================================="
    
    if check_command livekit-server && [[ "$FORCE_INSTALL" != true ]]; then
        echo "✅ LiveKit Server is already installed"
        return 0
    fi
    
    case $OS in
        "Darwin")
            echo "Installing LiveKit Server on macOS..."
            if check_command brew; then
                brew update && brew install livekit
            else
                echo "❌ Homebrew not installed. Please install Homebrew first"
                echo "Homebrew installation: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
                return 1
            fi
            ;;
        "Linux")
            echo "Installing LiveKit Server on Linux..."
            curl -sSL https://get.livekit.io | bash
            ;;
        *)
            echo "❌ Unsupported operating system: $OS"
            echo "Please manually install LiveKit Server: https://github.com/livekit/livekit/releases"
            return 1
            ;;
    esac
    
    echo "✅ LiveKit Server installation completed"
}

# Function: Determine Docker image
get_docker_image() {
    case $ARCH in
        "x86_64"|"amd64")
            echo "privoce/vocespace:latest"
            ;;
        "arm64"|"aarch64")
            echo "privoce/vocespace:latest_arm"
            ;;
        *)
            echo "❌ Unsupported architecture: $ARCH"
            echo "Supported architectures: x86_64, amd64, arm64, aarch64"
            exit 1
            ;;
    esac
}

# Function: Pull VoceSpace image
pull_vocespace_image() {
    echo "=========================================="
    echo "Pulling VoceSpace Docker Image"
    echo "=========================================="
    
    IMAGE=$(get_docker_image)
    echo "Pulling image: $IMAGE"
    
    docker pull "$IMAGE"
    echo "✅ Image pull completed"
}

# Function: Start VoceSpace container
start_vocespace_container() {
    echo "=========================================="
    echo "Starting VoceSpace Container"
    echo "=========================================="
    
    IMAGE=$(get_docker_image)
    CONTAINER_NAME="vocespace"
    
    # Check if container already exists
    if docker ps -a --format "table {{.Names}}" | grep -q "^$CONTAINER_NAME$"; then
        if [[ "$FORCE_INSTALL" == true ]]; then
            echo "Force mode: stopping and removing existing container..."
            docker stop "$CONTAINER_NAME" 2>/dev/null || true
            docker rm "$CONTAINER_NAME" 2>/dev/null || true
        else
            echo "Detected existing container $CONTAINER_NAME"
            read -p "Do you want to stop and remove the existing container? (y/n): " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                echo "Stopping and removing existing container..."
                docker stop "$CONTAINER_NAME" 2>/dev/null || true
                docker rm "$CONTAINER_NAME" 2>/dev/null || true
            else
                echo "Operation cancelled"
                return 1
            fi
        fi
    fi
    
    echo "Starting new container..."
    docker run -d \
        -p 3000:3000 \
        --name "$CONTAINER_NAME" \
        -v "$(pwd)/$CONFIG_FILE:/app/vocespace.conf.json" \
        "$IMAGE"
    
    echo "✅ VoceSpace container started successfully"
    echo "Container name: $CONTAINER_NAME"
    echo "Access URL: http://localhost:3000"
    echo "Access URL (LAN): http://$HOST_IP:3000"
}

# Function: Start LiveKit Server
start_livekit_server() {
    if [[ "$SKIP_LIVEKIT" == true ]]; then
        echo "⏭️  Skipping LiveKit Server startup"
        return 0
    fi
    
    echo "=========================================="
    echo "Starting LiveKit Server"
    echo "=========================================="
    
    echo "Checking if LiveKit Server is already running..."
    if pgrep -f "livekit-server" > /dev/null; then
        if [[ "$FORCE_INSTALL" == true ]]; then
            echo "Force mode: restarting LiveKit Server..."
            pkill -f "livekit-server" || true
            sleep 2
        else
            echo "⚠️  LiveKit Server is already running"
            read -p "Do you want to restart LiveKit Server? (y/n): " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                echo "Stopping existing LiveKit Server..."
                pkill -f "livekit-server" || true
                sleep 2
            else
                echo "Keeping existing LiveKit Server running"
                return 0
            fi
        fi
    fi
    
    echo "Starting LiveKit Server..."
    echo "Note: LiveKit Server will run in the background"
    echo "To stop it, use: pkill -f 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 started successfully"
        echo "Log file: $(pwd)/livekit-server.log"
    else
        echo "❌ LiveKit Server failed to start"
        echo "Please check log file: $(pwd)/livekit-server.log"
        return 1
    fi
}

# Function: Show deployment status
show_status() {
    echo "=========================================="
    echo "Deployment Status Check"
    echo "=========================================="
    
    echo "Docker container status:"
    docker ps --filter "name=vocespace" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    
    echo ""
    echo "Redis status:"
    if pgrep -f "redis-server" > /dev/null; then
        echo "✅ Redis is running"
    else
        echo "❌ Redis is not running"
    fi
    
    echo ""
    echo "LiveKit Server status:"
    if pgrep -f "livekit-server" > /dev/null; then
        echo "✅ LiveKit Server is running"
    else
        echo "❌ LiveKit Server is not running"
    fi
    
    echo ""
    echo "=========================================="
    echo "Access Information"
    echo "=========================================="
    echo "VoceSpace Application: http://localhost:3000"
    echo "VoceSpace Application (LAN): http://$HOST_IP:3000"
    echo "LiveKit Server: ws://$HOST_IP:7880"
    echo "Redis: $HOST_IP:6379"
    echo ""
    echo "To view container logs: docker logs vocespace"
    echo "To view LiveKit logs: tail -f livekit-server.log"
    echo "To view Redis logs: tail -f redis.log"
}

# Main function
main() {
    # Parse command line arguments
    parse_args "$@"
    
    echo "Starting deployment process..."
    
    # Show configuration information
    if [[ -n "$CONFIG_FILE" ]] || [[ -n "$HOST_IP" ]] || [[ "$FORCE_INSTALL" == true ]]; then
        echo "=========================================="
        echo "Configuration Information"
        echo "=========================================="
        [[ -n "$CONFIG_FILE" ]] && echo "Configuration file: $CONFIG_FILE"
        [[ -n "$HOST_IP" ]] && echo "Host IP: $HOST_IP"
        [[ "$FORCE_INSTALL" == true ]] && echo "Force installation: Enabled"
        [[ "$SKIP_REDIS" == true ]] && echo "Skip Redis: Yes"
        [[ "$SKIP_LIVEKIT" == true ]] && echo "Skip LiveKit: Yes"
        echo ""
    fi
    
    # Check Docker
    if ! check_docker; then
        exit 1
    fi
    
    # Detect host IP
    if ! detect_host_ip; then
        exit 1
    fi
    
    # Create configuration file
    if ! create_default_config; then
        echo "❌ Configuration file creation failed"
        exit 1
    fi
    
    # Install Redis
    if ! install_redis; then
        echo "❌ Redis installation failed"
        exit 1
    fi
    
    # Install LiveKit Server
    if ! install_livekit; then
        echo "❌ LiveKit Server installation failed"
        exit 1
    fi
    
    # Pull image
    if ! pull_vocespace_image; then
        echo "❌ Image pull failed"
        exit 1
    fi
    
    # Start container
    if ! start_vocespace_container; then
        echo "❌ Container startup failed"
        exit 1
    fi
    
    # Start LiveKit Server
    if ! start_livekit_server; then
        echo "❌ LiveKit Server startup failed"
        exit 1
    fi
    
    echo ""
    echo "Waiting for services to start..."
    sleep 5
    
    # Show status
    show_status
    
    echo ""
    echo "=========================================="
    echo "🎉 Deployment Complete!"
    echo "=========================================="
    echo "Please visit http://localhost:3000 in your browser"
    echo "Or visit http://$HOST_IP:3000 from other devices on the network"
    echo "If you encounter any issues, please check the relevant log files"
}

# Run main function
main "$@"
