#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DESKTOP_DIR="$ROOT_DIR/desktop"
TAURI_DIR="$DESKTOP_DIR/src-tauri"
CLEAN=0

for arg in "$@"; do
  case "$arg" in
    --clean)
      CLEAN=1
      ;;
    -h|--help)
      echo "usage: ./build.sh [--clean]"
      exit 0
      ;;
    *)
      echo "unknown argument: $arg" >&2
      exit 2
      ;;
  esac
done

log() {
  printf '[rho] %s\n' "$*"
}

if [[ "$CLEAN" == "1" ]]; then
  log "cleaning desktop Rust build"
  cargo clean --manifest-path "$TAURI_DIR/Cargo.toml"
fi

if [[ ! -d "$DESKTOP_DIR/node_modules" ]]; then
  log "installing desktop npm dependencies"
  (cd "$DESKTOP_DIR" && npm install)
fi

BUILD_ARGS=(build --config '{"bundle":{"createUpdaterArtifacts":false}}')
if [[ -n "${TAURI_TARGET:-}" ]]; then
  BUILD_ARGS+=(--target "$TAURI_TARGET")
fi

set +e
(cd "$DESKTOP_DIR" && npm exec -- tauri "${BUILD_ARGS[@]}")
status=$?
set -e

if [[ "$status" -ne 0 ]]; then
  if [[ "$(uname -s)" == "Darwin" ]] && find "$TAURI_DIR/target" -path "*/release/bundle/macos/*.app" -maxdepth 8 -print -quit 2>/dev/null | grep -q .; then
    log "Tauri packaging failed after app build; trying fallback DMG builder"
    "$ROOT_DIR/scripts/create-desktop-dmg.sh"
  else
    exit "$status"
  fi
fi

if [[ "$(uname -s)" == "Darwin" ]] && command -v xattr >/dev/null 2>&1; then
  find "$TAURI_DIR/target" \( -name "*.dmg" -o -name "*.app.tar.gz" -o -name "*.sig" \) -print0 2>/dev/null \
    | xargs -0 xattr -c 2>/dev/null || true
fi

log "desktop package outputs"
find "$TAURI_DIR/target" -maxdepth 8 -path "*/release/bundle/*" -type f -print 2>/dev/null | sort || true
