#!/usr/bin/env bash
# Build AyaanScriptPlus-Installer.dmg from the install.sh + README.
#
# Two paths:
#   1. On macOS  — uses hdiutil to make a proper UDIF .dmg
#   2. On Linux  — uses genisoimage to make an HFS/Apple hybrid image
#                  that modern macOS can still mount.
#
# The resulting .dmg drops users into a folder with install.sh and a README.
# They double-click install.sh (or run it from Terminal) to install AS+.

set -e

VERSION="1.36.0"
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
OUT="$SCRIPT_DIR/AyaanScriptPlus-Installer.dmg"
STAGE="$(mktemp -d)"
trap 'rm -rf "$STAGE"' EXIT

# Stage the install payload
mkdir -p "$STAGE/AyaanScriptPlus"
cp "$SCRIPT_DIR/install.sh" "$STAGE/AyaanScriptPlus/install.sh"
chmod +x "$STAGE/AyaanScriptPlus/install.sh"

cat > "$STAGE/AyaanScriptPlus/README.txt" <<EOF
AyaanScript+ v$VERSION — macOS/Linux Installer
================================================

To install, open Terminal in this folder and run:

    bash install.sh

This will:
  1. Install Rust via rustup (if not already present)
  2. Install ayaan and aspkg via 'cargo install ayaan'
  3. Add ~/.cargo/bin to your shell PATH

After installation, open a NEW terminal and try:

    ayaan                  - start the REPL
    ayaan myfile.ayaan     - run a script
    aspkg help             - package manager

Need help?
  https://github.com/ayaan511/AyaanScriptPlus
EOF

echo "[i] Staged payload at $STAGE/AyaanScriptPlus"
ls -la "$STAGE/AyaanScriptPlus"

if command -v hdiutil >/dev/null 2>&1; then
    echo "[i] Building DMG on macOS via hdiutil..."
    rm -f "$OUT"
    hdiutil create -volname "AyaanScriptPlus" \
                   -srcfolder "$STAGE/AyaanScriptPlus" \
                   -ov -format UDZO \
                   "$OUT"
elif command -v genisoimage >/dev/null 2>&1; then
    echo "[i] Building DMG on Linux via genisoimage (HFS hybrid)..."
    rm -f "$OUT"
    genisoimage -V "AyaanScriptPlus" \
                -D -R -apple -no-pad \
                -o "$OUT" \
                "$STAGE/AyaanScriptPlus"
else
    echo "[!] Neither hdiutil (macOS) nor genisoimage (Linux) found."
    echo "    Install genisoimage on Linux:"
    echo "      sudo dnf install genisoimage     # Fedora"
    echo "      sudo apt install genisoimage     # Debian/Ubuntu"
    exit 1
fi

if [ -f "$OUT" ]; then
    SIZE=$(du -h "$OUT" | cut -f1)
    echo ""
    echo "+============================================+"
    echo "|  DMG built: $(basename "$OUT")"
    echo "|  Size:      $SIZE"
    echo "|  Path:      $OUT"
    echo "+============================================+"
fi
