#!/bin/bash

# AI note: this script was generated with AI, and hand-edited

set -e  # Exit on error

PROJECT_NAME=$(grep name Cargo.toml | head -n 1 | cut -d '"' -f 2 || echo "rust-project")
VERSION=$(grep version Cargo.toml | head -n 1 | cut -d '"' -f 2 || echo "0.1.0")
OUTPUT_DIR="dist"
WINDOWS_TARGET="x86_64-pc-windows-gnu"
MACOS_TARGET="aarch64-apple-darwin"

mkdir -p "$OUTPUT_DIR"

echo "Building $PROJECT_NAME v$VERSION for multiple platforms..."

if ! command -v rustup &> /dev/null; then
    echo "Error: rustup is not installed. Please install Rust toolchain first."
    exit 1
fi

rustup target add "$WINDOWS_TARGET" || echo "Windows target already installed"
rustup target add "$MACOS_TARGET" || echo "macOS target already installed"

echo "Building for Windows (x86_64)..."
cargo build --release --target="$WINDOWS_TARGET"
WINDOWS_BIN_PATH="target/$WINDOWS_TARGET/release/$PROJECT_NAME.exe"

echo "Building for macOS (ARM64)..."
cargo build --release --target="$MACOS_TARGET"
MACOS_BIN_PATH="target/$MACOS_TARGET/release/$PROJECT_NAME"

if [ -f "$WINDOWS_BIN_PATH" ]; then
    echo "Packaging Windows binary..."
    WINDOWS_PACKAGE="$OUTPUT_DIR/${PROJECT_NAME}_${VERSION}_windows_x86_64"
    mkdir -p "$WINDOWS_PACKAGE"
    cp "$WINDOWS_BIN_PATH" "$WINDOWS_PACKAGE/"
    cp README.md UNLICENSE* "$WINDOWS_PACKAGE/" 2>/dev/null || true

    echo "Creating Windows zip archive..."
    (cd "$OUTPUT_DIR" && zip -r "${PROJECT_NAME}_${VERSION}_windows_x86_64.zip" "$(basename "$WINDOWS_PACKAGE")")

    echo "Creating Windows tar.gz archive..."
    (cd "$OUTPUT_DIR" && tar -czf "${PROJECT_NAME}_${VERSION}_windows_x86_64.tar.gz" "$(basename "$WINDOWS_PACKAGE")")

    rm -rf "$WINDOWS_PACKAGE"
    echo "Windows packages created:
    - $OUTPUT_DIR/${PROJECT_NAME}_${VERSION}_windows_x86_64.zip
    - $OUTPUT_DIR/${PROJECT_NAME}_${VERSION}_windows_x86_64.tar.gz"
else
    echo "Warning: Windows binary not found at $WINDOWS_BIN_PATH"
fi

if [ -f "$MACOS_BIN_PATH" ]; then
    echo "Packaging macOS binary..."
    MACOS_PACKAGE="$OUTPUT_DIR/${PROJECT_NAME}_${VERSION}_macos_arm64"
    mkdir -p "$MACOS_PACKAGE"
    cp "$MACOS_BIN_PATH" "$MACOS_PACKAGE/"
    cp README.md UNLICENSE* "$MACOS_PACKAGE/" 2>/dev/null || true

    echo "Creating macOS zip archive..."
    (cd "$OUTPUT_DIR" && zip -r "${PROJECT_NAME}_${VERSION}_macos_arm64.zip" "$(basename "$MACOS_PACKAGE")")

    echo "Creating macOS tar.gz archive..."
    (cd "$OUTPUT_DIR" && tar -czf "${PROJECT_NAME}_${VERSION}_macos_arm64.tar.gz" "$(basename "$MACOS_PACKAGE")")

    rm -rf "$MACOS_PACKAGE"
    echo "macOS packages created:
    - $OUTPUT_DIR/${PROJECT_NAME}_${VERSION}_macos_arm64.zip
    - $OUTPUT_DIR/${PROJECT_NAME}_${VERSION}_macos_arm64.tar.gz"
else
    echo "Warning: macOS binary not found at $MACOS_BIN_PATH"
fi

echo "Build and packaging complete! Check the $OUTPUT_DIR directory for the packaged binaries."
