#!/usr/bin/env bash
# Friendly SlicerVault installer for Debian/Ubuntu and other desktop Linux systems.
set -euo pipefail

VERSION="9.0.0"
BASE_URL="${SV_DOWNLOAD_BASE_URL:-https://slicervault-web.tail4157.ts.net/downloads/current}"

case "$(uname -m)" in
  x86_64|amd64) ARCH="x64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *) printf 'SlicerVault does not yet have a package for %s.\n' "$(uname -m)" >&2; exit 1 ;;
esac

if command -v curl >/dev/null 2>&1; then
  DOWNLOAD=(curl -fL --retry 3 --progress-bar)
elif command -v wget >/dev/null 2>&1; then
  DOWNLOAD=(wget -O)
else
  printf 'Install curl or wget, then run this installer again.\n' >&2
  exit 1
fi

download() {
  local url="$1" target="$2"
  if [ "${DOWNLOAD[0]}" = "wget" ]; then
    "${DOWNLOAD[@]}" "$target" "$url"
  else
    "${DOWNLOAD[@]}" "$url" -o "$target"
  fi
}

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

printf 'Installing SlicerVault %s Pro for Linux %s...\n' "$VERSION" "$ARCH"
if command -v apt-get >/dev/null 2>&1 && command -v dpkg >/dev/null 2>&1; then
  PACKAGE="$TMP_DIR/SlicerVault.deb"
  download "$BASE_URL/SlicerVault-Linux-${ARCH}.deb" "$PACKAGE"
  if command -v sudo >/dev/null 2>&1; then
    sudo apt-get install -y "$PACKAGE"
  elif [ "$(id -u)" -eq 0 ]; then
    apt-get install -y "$PACKAGE"
  else
    printf 'Debian/Ubuntu needs administrator approval. Re-run this installer from an account with sudo.\n' >&2
    exit 1
  fi
  printf 'Installed. Open SlicerVault from the applications menu.\n'
  exit 0
fi

APP_DIR="$HOME/.local/opt/slicervault"
BIN_DIR="$HOME/.local/bin"
APP_IMAGE="$APP_DIR/SlicerVault-${VERSION}-Pro-${ARCH}.AppImage"
mkdir -p "$APP_DIR" "$BIN_DIR" "$HOME/.local/share/applications"
download "$BASE_URL/SlicerVault-Linux-${ARCH}.AppImage" "$APP_IMAGE"
chmod 0755 "$APP_IMAGE"
ln -sfn "$APP_IMAGE" "$BIN_DIR/slicervault"

cat > "$HOME/.local/share/applications/slicervault.desktop" <<DESKTOP
[Desktop Entry]
Name=SlicerVault ${VERSION} Pro
Comment=3D printing vault and farm control
Exec=$APP_IMAGE
Terminal=false
Type=Application
Categories=Utility;Graphics;
StartupNotify=true
DESKTOP

printf 'Installed for this user. Open SlicerVault from the applications menu.\n'
if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
  printf 'You can also start it with: %s\n' "$APP_IMAGE"
else
  printf 'You can also start it with: slicervault\n'
fi
