#!/bin/bash
# Install Melexis Python packages to system Python

echo "Installing Melexis LIN packages to system Python..."

MELEXIS_SITE_PACKAGES="/mnt/WINDRV/InstalledPrograms/Melexis IDE/plugins/com.melexis.mlxide.python_1.2.0.202408130945/python/Lib/site-packages"

# Try to install from Melexis packages
if [ -d "$MELEXIS_SITE_PACKAGES" ]; then
    echo "Found Melexis packages at: $MELEXIS_SITE_PACKAGES"

    # Copy packages to system site-packages
    SYSTEM_SITE_PACKAGES=$(python3 -c "import site; print(site.getsitepackages()[0])" 2>/dev/null)

    if [ -z "$SYSTEM_SITE_PACKAGES" ]; then
        echo "Error: Could not determine system site-packages directory"
        exit 1
    fi

    echo "System site-packages: $SYSTEM_SITE_PACKAGES"

    # Check if we have write permissions
    if [ ! -w "$SYSTEM_SITE_PACKAGES" ]; then
        echo "Note: You may need sudo to install packages system-wide"
        SUDO="sudo"
    else
        SUDO=""
    fi

    # Copy packages
    echo "Copying pylin..."
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylin" "$SYSTEM_SITE_PACKAGES/"
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylin-"*".dist-info" "$SYSTEM_SITE_PACKAGES/"

    echo "Copying pylinframe..."
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylinframe" "$SYSTEM_SITE_PACKAGES/"
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylinframe-"*".dist-info" "$SYSTEM_SITE_PACKAGES/"

    echo "Copying pymumclient..."
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pymumclient" "$SYSTEM_SITE_PACKAGES/"
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pymumclient-"*".dist-info" "$SYSTEM_SITE_PACKAGES/"

    # Copy all dependencies
    echo "Copying all Melexis dependencies..."
    for pkg_dir in "$MELEXIS_SITE_PACKAGES"/*; do
        pkg=$(basename "$pkg_dir")

        # Skip dist-info directories and __pycache__
        if [[ "$pkg" == *".dist-info" ]] || [[ "$pkg" == "__pycache__" ]]; then
            continue
        fi

        # Only copy directories (packages)
        if [ -d "$pkg_dir" ]; then
            echo "  - $pkg"
            $SUDO cp -r "$pkg_dir" "$SYSTEM_SITE_PACKAGES/"
            # Copy corresponding .dist-info if exists
            $SUDO cp -r "$MELEXIS_SITE_PACKAGES/${pkg}-"*".dist-info" "$SYSTEM_SITE_PACKAGES/" 2>/dev/null || true
        fi
    done

    echo ""
    echo "Installation complete!"
    echo ""
    echo "Verifying installation..."
    python3 -c "import pylin; import pymumclient; print('✓ Packages imported successfully')" && echo "Success!" || echo "Failed - some packages missing"

else
    echo "Error: Melexis packages not found"
    exit 1
fi