#!/bin/sh
# SoundNinja installer for NixOS (AppImage, no root needed).
# Usage: curl -fsSL https://soundninja.marcus-universe.com/install/nixos.sh | sh
set -eu

# Everything runs from main, so a download cut off half way executes nothing.
main() {
  base="https://github.com/marcus-universe/SoundNinja/releases/latest/download"
  dir="$HOME/Applications"
  app="$dir/SoundNinja.AppImage"
  entry="${XDG_DATA_HOME:-$HOME/.local/share}/applications/soundninja.desktop"

  command -v curl >/dev/null 2>&1 || fail "curl not found."

  case "$(uname -m)" in
    x86_64) arch=amd64 ;;
    aarch64 | arm64) arch=arm64 ;;
    *) fail "No AppImage for CPU architecture '$(uname -m)'." ;;
  esac

  mkdir -p "$dir" "$(dirname "$entry")"

  echo "Downloading soundninja-linux-$arch.AppImage ..."
  # Download next to the target, then swap: a running copy is never half written.
  curl -fL --progress-bar -o "$app.part" "$base/soundninja-linux-$arch.AppImage"
  chmod +x "$app.part"
  mv -f "$app.part" "$app"

  # NixOS cannot start an AppImage directly unless programs.appimage.binfmt is on.
  if command -v appimage-run >/dev/null 2>&1; then
    run="appimage-run \"$app\""
  else
    run="\"$app\""
    needs_runner=1
  fi
  cat >"$entry" <<DESKTOP
[Desktop Entry]
Type=Application
Name=Sound Ninja
Comment=Open source soundboard
Exec=$run
Terminal=false
Categories=AudioVideo;Audio;
DESKTOP

  echo "Done. Installed to $app"
  if [ "${needs_runner:-0}" = 1 ]; then
    echo "appimage-run is not installed. Either set programs.appimage.enable and"
    echo "programs.appimage.binfmt to true in configuration.nix, or start it with:"
    echo "  nix-shell -p appimage-run --run \"appimage-run $app\""
  else
    echo "Start Sound Ninja from the app menu."
  fi
}

fail() {
  echo "Error: $1" >&2
  exit 1
}

main "$@"
