#!/bin/bash
# Build Linux desktop packages (deb + rpm) for JellyTau.
#
# Produces bundles under src-tauri/target/release/bundle/{deb,rpm}.
# Runs on the existing Ubuntu builder image. NOTE: Tauri has no pacman bundle
# target — the Arch package is built separately with makepkg (scripts/build-arch.sh
# / Dockerfile.arch). `appimage` is also available if you want a portable bundle.
#
# Usage:
#   scripts/build-desktop-linux.sh                 # deb + rpm
#   BUNDLES="deb,appimage" scripts/build-desktop-linux.sh # subset / add appimage
#   OUTPUT_DIR=/app/dist scripts/build-desktop-linux.sh   # copy bundles out
set -euo pipefail

cd "$(dirname "$0")/.."

BUNDLES="${BUNDLES:-deb,rpm}"

echo "🐧 Building JellyTau Linux desktop packages"
echo "==========================================="
echo "Bundles: $BUNDLES"
echo ""

bun install --frozen-lockfile 2>/dev/null || bun install
bun run build

# --bundles overrides tauri.conf.json bundle.targets so this script controls
# exactly which Linux formats are produced (never NSIS here).
bun run tauri build --bundles "$BUNDLES"

BUNDLE_ROOT="src-tauri/target/release/bundle"
echo ""
echo "✅ Built packages:"
find "$BUNDLE_ROOT" -maxdepth 2 -type f \
  \( -name '*.deb' -o -name '*.rpm' -o -name '*.AppImage' \) -print

if [[ -n "${OUTPUT_DIR:-}" ]]; then
  mkdir -p "$OUTPUT_DIR"
  find "$BUNDLE_ROOT" -maxdepth 2 -type f \
    \( -name '*.deb' -o -name '*.rpm' -o -name '*.AppImage' \) \
    -exec cp -v {} "$OUTPUT_DIR/" \;
  echo ""
  echo "📦 Copied bundles to $OUTPUT_DIR"
fi
