#!/bin/sh
# SoundNinja installer for Arch Linux and derivatives.
# Usage: curl -fsSL https://soundninja.marcus-universe.com/install/arch.sh | sh
set -eu

# Everything runs from main, so a download cut off half way executes nothing.
main() {
  api="https://api.github.com/repos/marcus-universe/SoundNinja/releases/latest"

  command -v pacman >/dev/null 2>&1 || fail "pacman not found. This script is for Arch based systems."
  command -v curl >/dev/null 2>&1 || fail "curl not found. Install it with: sudo pacman -S curl"

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

  # Package names carry the version, so ask GitHub for the current one.
  url=$(curl -fsSL "$api" |
    grep -oE "https://[^\"]+/soundninja-bin-[^\"]+-$arch\.pkg\.tar\.(zst|xz)" |
    head -n1) || true
  [ -n "$url" ] || fail "Could not find a package for $arch in the latest release."

  tmp=$(mktemp -d)
  trap 'rm -rf "$tmp"' EXIT

  file=${url##*/}
  echo "Downloading $file ..."
  curl -fL --progress-bar -o "$tmp/$file" "$url"

  echo "Installing (asks for your password) ..."
  sudo pacman -U --noconfirm "$tmp/$file"

  echo "Done. Start Sound Ninja from the app menu, or run: soundninja"
}

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

main "$@"
