#!/usr/bin/env bash
#
# Package realm for distribution.
#
# Usage:
#   ./package.sh                    # Build for current platform
#   ./package.sh <target>           # Cross-compile for a specific target
#
# Examples:
#   ./package.sh
#   ./package.sh x86_64-unknown-linux-gnu
#   ./package.sh x86_64-pc-windows-gnu
#   ./package.sh aarch64-apple-darwin
#
# Produces: dist/realm-<target>.<tar.gz|zip>

set -euo pipefail

TARGET="${1:-$(rustc -vV | grep '^host:' | cut -d' ' -f2)}"
VERSION="$(cargo metadata --format-version=1 --no-deps | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4)"
ARCHIVE_NAME="realm-${VERSION}-${TARGET}"
DIST_DIR="dist"
STAGE_DIR="${DIST_DIR}/${ARCHIVE_NAME}"

echo "Building realm ${VERSION} for ${TARGET}..."

if [ "$TARGET" = "$(rustc -vV | grep '^host:' | cut -d' ' -f2)" ]; then
    cargo build --release
else
    cargo build --release --target "$TARGET"
fi

# Determine binary path and extension
if [[ "$TARGET" == *"windows"* ]]; then
    BIN_NAME="realm.exe"
else
    BIN_NAME="realm"
fi

if [ "$TARGET" = "$(rustc -vV | grep '^host:' | cut -d' ' -f2)" ]; then
    BIN_PATH="target/release/${BIN_NAME}"
else
    BIN_PATH="target/${TARGET}/release/${BIN_NAME}"
fi

# Stage the archive contents
rm -rf "$STAGE_DIR"
mkdir -p "$STAGE_DIR"
cp "$BIN_PATH" "$STAGE_DIR/"
cp -r data "$STAGE_DIR/"

# Create archive
cd "$DIST_DIR"
if [[ "$TARGET" == *"windows"* ]]; then
    zip -r "${ARCHIVE_NAME}.zip" "$ARCHIVE_NAME"
    echo "Created ${DIST_DIR}/${ARCHIVE_NAME}.zip"
else
    tar czf "${ARCHIVE_NAME}.tar.gz" "$ARCHIVE_NAME"
    echo "Created ${DIST_DIR}/${ARCHIVE_NAME}.tar.gz"
fi

rm -rf "$ARCHIVE_NAME"
