#!/usr/bin/env bash
# Build AyaanScript+ installer artifacts that work reliably:
#   - AyaanScriptPlus-Installer.zip       — universal, opens on every macOS/Linux/Windows
#   - AyaanScriptPlus-Installer.tar.gz    — for Linux users
#   - AyaanScriptPlus-Installer.dmg       — best-effort (real on macOS, ISO on Linux)
set -e

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

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:

  1. Open Terminal in this folder
  2. Run:    bash install.sh

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

If your system blocks the script with "permission denied":
  chmod +x install.sh
  ./install.sh

For Windows: use AyaanScriptPlus-Setup.exe instead.

Repo: https://github.com/ayaan511/AyaanScriptPlus
EOF

echo "[i] Staged payload."

# --- ZIP (universal — works on any OS, no quarantine drama on most setups) ---
ZIP_OUT="$SCRIPT_DIR/AyaanScriptPlus-Installer.zip"
rm -f "$ZIP_OUT"
( cd "$STAGE" && zip -r "$ZIP_OUT" AyaanScriptPlus > /dev/null )
echo "[+] $(basename "$ZIP_OUT")  $(du -h "$ZIP_OUT" | cut -f1)"

# --- tar.gz (idiomatic Linux/macOS) ---
TGZ_OUT="$SCRIPT_DIR/AyaanScriptPlus-Installer.tar.gz"
rm -f "$TGZ_OUT"
tar -czf "$TGZ_OUT" -C "$STAGE" AyaanScriptPlus
echo "[+] $(basename "$TGZ_OUT")  $(du -h "$TGZ_OUT" | cut -f1)"

# --- DMG (best-effort; real on macOS via hdiutil, ISO fallback on Linux) ---
DMG_OUT="$SCRIPT_DIR/AyaanScriptPlus-Installer.dmg"
rm -f "$DMG_OUT"
if command -v hdiutil >/dev/null 2>&1; then
    hdiutil create -volname "AyaanScriptPlus" \
                   -srcfolder "$STAGE/AyaanScriptPlus" \
                   -ov -format UDZO \
                   "$DMG_OUT"
    echo "[+] $(basename "$DMG_OUT")  $(du -h "$DMG_OUT" | cut -f1)   (real UDIF DMG via hdiutil)"
elif command -v genisoimage >/dev/null 2>&1; then
    genisoimage -V "AyaanScriptPlus" -D -R -apple -no-pad \
                -o "$DMG_OUT" "$STAGE/AyaanScriptPlus" 2>&1 | tail -3
    echo "[!] $(basename "$DMG_OUT")  $(du -h "$DMG_OUT" | cut -f1)   (ISO 9660 fallback — modern macOS may refuse)"
    echo "    For a real .dmg, run this script on a Mac."
fi

echo ""
echo "Done. Ship the .zip — it's the most reliable format on locked-down machines."
