#!/usr/bin/env bash

# install-desktop - Automatically install MUSACode Desktop client
# Supports macOS, Windows, Linux multiple architectures
# Usage: curl -fsSL https://example.com/install-desktop | bash
# Or: curl -fsSL https://example.com/install-desktop | bash -s -- --version 1.0.0.rc.1

set -euo pipefail

# Default version
VERSION="latest"
TOS_BUCKET="musacode.tos-cn-beijing.volces.com"

# Platform description map
declare -A PLATFORM_DESC=(
    # ["darwin-arm64"]="macOS (Apple Silicon)"
    # ["darwin-x86_64"]="macOS (Intel)"
    ["windows-x86_64"]="Windows (x64)"
    ["linux-x86_64-deb"]="Linux x86 (.deb)"
    ["linux-x86_64-rpm"]="Linux x86 (.rpm)"
    ["linux-aarch64-rpm"]="Linux arm64 (.rpm)"
    ["linux-aarch64-deb"]="Linux arm64 (.deb)"
)

# Show help information
show_help() {
    cat << EOF
MUSACode Desktop Installation Script

Usage:
  curl -fsSL https://example.com/install-desktop | bash
  curl -fsSL https://example.com/install-desktop | bash -s -- --version <version>
  curl -fsSL https://example.com/install-desktop | bash -s -- --help

Parameters:
  --version <version>  Specify installation version (default: latest)
  --help               Show this help message

Examples:
  # Install the latest version
  curl -fsSL https://example.com/install-desktop | bash
  
  # Install a specific version
  curl -fsSL https://example.com/install-desktop | bash -s -- --version 1.0.0.rc.1
EOF
}

# Parse command line arguments
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --version)
                if [[ -n "${2:-}" ]]; then
                    VERSION="$2"
                    shift 2
                else
                    echo "Error: --version parameter requires a version number"
                    exit 1
                fi
                ;;
            --help)
                show_help
                exit 0
                ;;
            *)
                echo "Error: Unknown parameter $1"
                show_help
                exit 1
                ;;
        esac
    done
}

# Detect platform and architecture
detect_platform() {
    local os_name
    local arch
    local pkg_manager=""

    # Detect operating system
    case "$(uname -s)" in
        Linux*)
            os_name="linux"
            # Detect Linux distribution package manager
            if command -v apt-get &> /dev/null; then
                pkg_manager="deb"
            elif command -v yum &> /dev/null || command -v dnf &> /dev/null; then
                pkg_manager="rpm"
            fi
            ;;
        Darwin*)
            os_name="darwin"
            ;;
        MINGW*|MSYS*|CYGWIN*)
            os_name="windows"
            ;;
        *)
            echo "Error: Unsupported operating system: $(uname -s)"
            exit 1
            ;;
    esac
    
    # Detect architecture
    case "$(uname -m)" in
        x86_64|amd64)
            arch="x86_64"
            ;;
        aarch64|arm64)
            arch="aarch64"
            ;;
        armv7l|armv8l)
            arch="arm"
            ;;
        *)
            echo "Error: Unsupported architecture: $(uname -m)"
            exit 1
            ;;
    esac
    
    # Build platform identifier
    if [[ "$os_name" == "linux" && -n "$pkg_manager" ]]; then
        PLATFORM="${os_name}-${arch}-${pkg_manager}"
    else
        PLATFORM="${os_name}-${arch}"
    fi
}

# Download file
download_file() {
    local url="$1"
    local output="$2"

    echo "Downloading: $url"
    
    if command -v curl &> /dev/null; then
        curl -fL "$url" -o "$output"
    elif command -v wget &> /dev/null; then
        wget "$url" -O "$output"
    else
        echo "Error: curl or wget is required to download files"
        exit 1
    fi
    
    if [[ $? -ne 0 ]]; then
        echo "Error: Download failed"
        exit 1
    fi
}

# Install package
install_package() {
    local package_file="$1"
    local platform="$2"

    echo "Installing: $package_file"
    
    case "$platform" in
        darwin*)
            # macOS installation
            if [[ "$package_file" == *.dmg ]]; then
                echo "Please manually mount and install the DMG file: $package_file"
                echo "Or use the following commands:"
                echo "  hdiutil attach \"$package_file\""
                echo "  # Then drag the app to the Applications folder"
            fi
            ;;
        windows*)
            # Windows installation
            if [[ "$package_file" == *.exe ]]; then
                echo "Installation package downloaded to: $package_file"
                echo "Please double-click to run the installer: $package_file"
            fi
            ;;
        linux*)
            if [ "$USER" != "root" ]; then
                user="$USER"
            else
                user="$SUDO_USER"
            fi

            if [ -n "$user" ]; then
                dir_path="/home/${user}/.local/share/musacode"
                if [ ! -d "$dir_path" ]; then
                    echo "Directory does not exist, create it: $dir_path"
                    sudo mkdir -p ${dir_path}/{bin,log,snapshot,storage,tool-output} && sudo touch ${dir_path}/musacode.db
                    sudo chown -R ${user}:${user} ${dir_path}
                fi
            fi

            # Linux installation
            if [[ "$package_file" == *.deb ]]; then
                sudo dpkg --remove musacode
                sudo dpkg --remove musacode-desktop-electron
                if command -v sudo &> /dev/null; then
                    sudo dpkg -i "$package_file" || sudo apt-get install -f -y
                else
                    dpkg -i "$package_file" || apt-get install -f -y
                fi
            elif [[ "$package_file" == *.rpm ]]; then
                if command -v sudo &> /dev/null; then
                    if command -v dnf &> /dev/null; then
                        sudo dnf install -y "$package_file"
                    else
                        sudo rpm -i "$package_file" || sudo yum install -y "$package_file"
                    fi
                else
                    rpm -i "$package_file" || yum install -y "$package_file"
                fi
            fi
            ;;
    esac
    
    echo "Installation complete!"
}

# Get Windows desktop path
get_windows_desktop_path() {
    local desktop_path=""
    
    # Try multiple methods to get desktop path
    if [[ -n "$USERPROFILE" ]]; then
        # Method 1: Use USERPROFILE environment variable
        desktop_path="$USERPROFILE/Desktop"
    elif [[ -n "$HOME" ]]; then
        # Method 2: Use HOME environment variable
        desktop_path="$HOME/Desktop"
    else
        # Method 3: Use PowerShell to get desktop path
        if command -v powershell &> /dev/null; then
            desktop_path=$(powershell -Command "[Environment]::GetFolderPath('Desktop')" 2>/dev/null | tr -d '\r\n')
        fi
    fi
    
    # Fallback to current directory if desktop not found
    if [[ -z "$desktop_path" ]] || [[ ! -d "$desktop_path" ]]; then
        echo "Warning: Desktop directory not found, using current directory instead."
        desktop_path="."
    fi
    
    echo "$desktop_path"
}

# Main function
main() {
    # Parse arguments
    parse_args "$@"

    # Detect platform
    detect_platform

    # Build download URL
    if [[ "$VERSION" == "latest" ]]; then
        specific_version=$(curl -sfL "https://${TOS_BUCKET}/desktop/latest" | tr -d '[:space:]')
        specific_version="${specific_version#v}"
        if [ -z "$specific_version" ]; then
            echo -e "Error: Failed to fetch latest version"
            exit 1
        fi
        VERSION=${specific_version}
    fi

    # Package map
    declare -A PACKAGE_MAP=(
        # macOS
        # ["darwin-arm64"]="MUSACode Desktop.dmg"
        # ["darwin-x86_64"]="MUSACode Desktop.dmg"
        
        # Windows
        ["windows-x86_64"]="MUSACode_${VERSION}_x64-setup.exe"
        
        # Linux
        ["linux-x86_64-deb"]="musacode-electron-linux-amd64-${VERSION}.deb"
        ["linux-x86_64-rpm"]="musacode-electron-linux-x86_64-${VERSION}.rpm"
        ["linux-aarch64-rpm"]="musacode-electron-linux-aarch64-${VERSION}.rpm"
        ["linux-aarch64-deb"]="musacode-electron-linux-arm64-${VERSION}.deb"
    )

    # Check if platform is supported
    if [[ -z "${PACKAGE_MAP[$PLATFORM]:-}" ]]; then
        echo "Error: Unsupported platform: $PLATFORM"
        echo "Supported platforms:"
        for key in "${!PLATFORM_DESC[@]}"; do
            echo "  - ${PLATFORM_DESC[$key]}"
        done
        exit 1
    fi

    PACKAGE_NAME="${PACKAGE_MAP[$PLATFORM]}"
    PLATFORM_DESC_TEXT="${PLATFORM_DESC[$PLATFORM]}"
    
    echo "========================================="
    echo "MUSACode Desktop Installer"
    echo "========================================="
    echo "Version:        $VERSION"
    echo "Detected platform:  $PLATFORM_DESC_TEXT"
    echo "Package:      $PACKAGE_NAME"
    echo "========================================="
    echo ""

    DOWNLOAD_URL="https://${TOS_BUCKET}/desktop/v${VERSION}/${PLATFORM}/${PACKAGE_NAME}"

    echo "DOWNLOAD URL: ${DOWNLOAD_URL}"

    # Set output path based on platform
    if [[ "$PLATFORM" == windows* ]]; then
        # For Windows: download to desktop
        DESKTOP_DIR=$(get_windows_desktop_path)
        OUTPUT_FILE="${DESKTOP_DIR}/${PACKAGE_NAME}"
        echo "Downloading to desktop: $OUTPUT_FILE"
    else
        # For other platforms: use temporary directory
        TEMP_DIR=$(mktemp -d)
        OUTPUT_FILE="${TEMP_DIR}/${PACKAGE_NAME}"
        
        # Cleanup function for non-Windows platforms
        cleanup() {
            if [[ -d "$TEMP_DIR" ]]; then
                rm -rf "$TEMP_DIR"
            fi
        }
        trap cleanup EXIT
    fi
    
    # Download and install
    download_file "$DOWNLOAD_URL" "$OUTPUT_FILE"
    install_package "$OUTPUT_FILE" "$PLATFORM"
}

main "$@"