#!/bin/bash
# Setup ARM64 cross-compilation toolchain for building msger on WSL/Linux

echo "🔧 Setting up ARM64 cross-compilation toolchain..."

# Detect distro
if [ -f /etc/os-release ]; then
    . /etc/os-release
    DISTRO=$ID
else
    echo "❌ Cannot detect Linux distribution"
    exit 1
fi

echo "📍 Detected distribution: $DISTRO"

# Install cross-compilation tools based on distro
case "$DISTRO" in
    ubuntu|debian)
        echo "📦 Installing packages for Debian/Ubuntu..."
        sudo apt update

        # Add arm64 architecture
        sudo dpkg --add-architecture arm64
        sudo apt update

        # Install cross-compilation tools
        sudo apt install -y \
            gcc-aarch64-linux-gnu \
            g++-aarch64-linux-gnu \
            libc6-dev-arm64-cross \
            pkg-config

        # Install ARM64 libraries for cross-compilation
        sudo apt install -y \
            libwebkit2gtk-4.1-dev:arm64 \
            libgtk-3-dev:arm64 \
            libglib2.0-dev:arm64 \
            libcairo2-dev:arm64 \
            libpango1.0-dev:arm64 \
            libgdk-pixbuf-2.0-dev:arm64 \
            libsoup-3.0-dev:arm64 \
            libjavascriptcoregtk-4.1-dev:arm64
        ;;
    fedora|rhel|centos)
        echo "📦 Installing packages for Fedora/RHEL..."
        sudo dnf install -y \
            gcc-aarch64-linux-gnu \
            gcc-c++-aarch64-linux-gnu \
            webkit2gtk4.1-devel \
            gtk3-devel \
            pkg-config
        ;;
    arch|manjaro)
        echo "📦 Installing packages for Arch..."
        sudo pacman -S --needed \
            aarch64-linux-gnu-gcc \
            webkit2gtk \
            gtk3 \
            pkg-config
        ;;
    *)
        echo "❌ Unsupported distribution: $DISTRO"
        echo "   Please install ARM64 cross-compilation tools manually"
        exit 1
        ;;
esac

# Add Rust ARM64 target
echo "🦀 Adding Rust ARM64 target..."
# Source cargo environment in case Rust was just installed
export PATH="$HOME/.cargo/bin:$PATH"
rustup target add aarch64-unknown-linux-gnu

# Configure cargo for ARM64 cross-compilation
echo "⚙️  Configuring cargo for ARM64 cross-compilation..."
mkdir -p ~/.cargo
cat > ~/.cargo/config.toml << 'EOF'
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
EOF

echo ""
echo "✅ ARM64 toolchain setup complete!"
echo ""
echo "You can now build ARM64 binaries with:"
echo "  npm run build:native:arm64"
echo ""
