#!/usr/bin/env bash
# Copyright (c) 2026 Antheas Kapanekakis. All rights reserved.

set -Eeuo pipefail

# Installer paths and names.
readonly SELF=$(readlink -f "${BASH_SOURCE[0]}")
readonly TITLE="Sunshine Installer"
readonly INSTALL_ROOT="/opt/sunshine"
readonly MARKER="${INSTALL_ROOT}/.installed-by-sunshine-desktop"
readonly CURRENT_BINARY="${INSTALL_ROOT}/current/usr/bin/sunshine"
readonly SERVICE="sunshine.service"
readonly LEGACY_SERVICE="app-dev.lizardbyte.app.Sunshine.service"
readonly RELEASE_API="https://api.github.com/repos/LizardByte/Sunshine/releases/latest"
readonly ICON_FILE="system-software-install"

# Mutable state cleaned up when the installer exits.
WORK_DIR=""
DIALOG=""
INSTALLING_PID=""
RELEASE_TAG=""
RELEASE_URL=""
RELEASE_SHA256=""
RELEASE_FILE=""

cleanup() {
  close_installing
  if [[ -n "${WORK_DIR}" && -d "${WORK_DIR}" ]]; then
    rm -rf -- "${WORK_DIR}"
  fi
}
trap cleanup EXIT

# Dialog helpers. KDialog is preferred on Plasma; Zenity is the fallback.
select_dialog() {
  if command -v kdialog >/dev/null 2>&1; then
    DIALOG="kdialog"
  elif command -v zenity >/dev/null 2>&1; then
    DIALOG="zenity"
  else
    printf '%s\n' "${TITLE} requires KDialog or Zenity." >&2
    exit 1
  fi
}

show_info() {
  if [[ "${DIALOG}" == "kdialog" ]]; then
    kdialog --title "${TITLE}" --icon "${ICON_FILE}" --msgbox "$1"
  else
    zenity --info --title="${TITLE}" --icon="${ICON_FILE}" --text="$1"
  fi
}

show_error() {
  if [[ "${DIALOG}" == "kdialog" ]]; then
    kdialog --title "${TITLE}" --icon "${ICON_FILE}" --error "$1"
  else
    zenity --error --title="${TITLE}" --icon="${ICON_FILE}" --text="$1"
  fi
}

show_installing() {
  if [[ "${DIALOG}" == "kdialog" ]]; then
    kdialog --title "${TITLE}" --icon "${ICON_FILE}" --msgbox "Installing Sunshine…\n\nPlease wait." >/dev/null 2>&1 &
  else
    zenity --info --title="${TITLE}" --icon="${ICON_FILE}" --text="Installing Sunshine…\n\nPlease wait." >/dev/null 2>&1 &
  fi
  INSTALLING_PID=$!
}

close_installing() {
  if [[ -n "${INSTALLING_PID}" ]] && kill -0 "${INSTALLING_PID}" >/dev/null 2>&1; then
    kill "${INSTALLING_PID}" >/dev/null 2>&1 || true
    wait "${INSTALLING_PID}" 2>/dev/null || true
  fi
  INSTALLING_PID=""
}

choose_installed_action() {
  local installed_version
  local status=0
  installed_version=$(sed -n 's/^version=//p' "${MARKER}" | head -n 1)

  if [[ "${DIALOG}" == "kdialog" ]]; then
    kdialog --title "${TITLE}" --icon "${ICON_FILE}" --yesnocancel "Sunshine ${installed_version:-unknown} is installed." --yes-label "Update" --no-label "Uninstall" --cancel-label "Cancel" || status=$?
    case ${status} in
      0) printf 'update' ;;
      1) printf 'uninstall' ;;
      *) return 1 ;;
    esac
  else
    local choice
    if choice=$(zenity --question --switch --title="${TITLE}" --icon="${ICON_FILE}" --text="Sunshine ${installed_version:-unknown} is installed." --extra-button="Update" --extra-button="Uninstall"); then
      :
    elif [[ -z "${choice}" ]]; then
      return 1
    fi
    case ${choice} in
      Update) printf 'update' ;;
      Uninstall) printf 'uninstall' ;;
      *) return 1 ;;
    esac
  fi
}

confirm_install() {
  if [[ "${DIALOG}" == "kdialog" ]]; then
    kdialog --title "${TITLE}" --icon "${ICON_FILE}" --yesno "Install the latest stable Sunshine release?" --yes-label "Install" --no-label "Cancel"
  else
    zenity --question --title="${TITLE}" --icon="${ICON_FILE}" --text="Install the latest stable Sunshine release?" --ok-label="Install" --cancel-label="Cancel"
  fi
}

choose_action() {
  if [[ -f "${MARKER}" && -x "${CURRENT_BINARY}" ]]; then
    choose_installed_action
  elif confirm_install; then
    printf 'install'
  else
    return 1
  fi
}

confirm_uninstall() {
  local text="Uninstall Sunshine? Your configuration and pairing state in ~/.config/sunshine will be preserved."
  if [[ "${DIALOG}" == "kdialog" ]]; then
    kdialog --title "${TITLE}" --icon "${ICON_FILE}" --warningyesno "${text}" --yes-label "Uninstall" --no-label "Cancel"
  else
    zenity --question --title="${TITLE}" --icon="dialog-warning" --text="${text}" --ok-label="Uninstall" --cancel-label="Cancel"
  fi
}

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    show_error "Required command not found: $1"
    exit 1
  fi
}

# Fetch and independently verify the latest stable AppImage.
fetch_release() {
  local metadata asset digest actual architecture asset_name

  architecture=$(uname -m)
  case "${architecture}" in
    x86_64 | aarch64) ;;
    *)
      show_error "Sunshine AppImages are not supported on ${architecture}."
      return 1
      ;;
  esac

  metadata=$(curl --fail --silent --show-error --location --retry 3 --connect-timeout 15 "${RELEASE_API}") || {
    show_error "Could not retrieve the latest Sunshine release."
    return 1
  }
  RELEASE_TAG=$(jq --exit-status --raw-output '.tag_name' <<<"${metadata}") || return 1
  asset=$(jq --exit-status --arg arch "${architecture}" '
    [.assets[] | select(.name | test("^sunshine.*[_-]" + $arch + "\\.appimage$"; "i"))]
    | if length == 1 then .[0] else empty end
  ' <<<"${metadata}") || {
    show_error "Sunshine ${RELEASE_TAG} does not contain a unique ${architecture} AppImage."
    return 1
  }
  asset_name=$(jq --exit-status --raw-output '.name' <<<"${asset}") || return 1

  RELEASE_URL=$(jq --exit-status --raw-output '.browser_download_url' <<<"${asset}") || return 1
  digest=$(jq --exit-status --raw-output '.digest' <<<"${asset}") || return 1
  RELEASE_SHA256=${digest#sha256:}

  if [[ ! "${RELEASE_TAG}" =~ ^[A-Za-z0-9._-]+$ || ! "${RELEASE_SHA256}" =~ ^[A-Fa-f0-9]{64}$ ]]; then
    show_error "GitHub returned invalid release metadata."
    return 1
  fi

  RELEASE_FILE="${WORK_DIR}/sunshine.AppImage"
  if ! curl --fail --show-error --location --retry 3 --connect-timeout 15 --output "${RELEASE_FILE}" "${RELEASE_URL}"; then
    show_error "Could not download ${asset_name}."
    return 1
  fi

  actual=$(sha256sum "${RELEASE_FILE}")
  actual=${actual%% *}
  if [[ "${actual,,}" != "${RELEASE_SHA256,,}" ]]; then
    show_error "The downloaded AppImage failed SHA-256 verification."
    return 1
  fi
  chmod 0700 "${RELEASE_FILE}"
}

# Only the payload below the marker is sent through Polkit.
run_privileged() {
  sed -n '/^# --- Privileged installer payload ---$/,$p' "${SELF}" | pkexec /usr/bin/bash -s -- "$@"
}

# User service lifecycle stays outside the privileged payload.
migrate_legacy_service() {
  systemctl --user disable --now "${LEGACY_SERVICE}" >/dev/null 2>&1 || true
  rm -f -- "${HOME}/.config/systemd/user/${LEGACY_SERVICE}"
  local legacy_alias="${HOME}/.config/systemd/user/sunshine.service"
  if [[ -L "${legacy_alias}" && $(readlink "${legacy_alias}") == *"${LEGACY_SERVICE}"* ]]; then
    rm -f -- "${legacy_alias}"
  fi
}

activate_service() {
  local action=$1

  migrate_legacy_service
  systemctl --user daemon-reload
  systemctl --user enable "${SERVICE}"

  if [[ "${action}" == "install" ]]; then
    systemctl --user start "${SERVICE}"
  else
    systemctl --user restart "${SERVICE}"
  fi
}

uninstall() {
  confirm_uninstall || return 0

  local was_enabled="no"
  local was_active="no"

  systemctl --user is-enabled --quiet "${SERVICE}" && was_enabled="yes"
  systemctl --user is-active --quiet "${SERVICE}" && was_active="yes"
  systemctl --user disable --now "${SERVICE}" >/dev/null 2>&1 || true
  if ! run_privileged uninstall; then
    systemctl --user daemon-reload
    [[ "${was_enabled}" == "yes" ]] && systemctl --user enable "${SERVICE}" >/dev/null 2>&1 || true
    [[ "${was_active}" == "yes" ]] && systemctl --user start "${SERVICE}" >/dev/null 2>&1 || true
    show_error "Uninstallation was canceled or failed."
    return 1
  fi

  systemctl --user daemon-reload
  systemctl --user reset-failed >/dev/null 2>&1 || true
  show_info "Sunshine was uninstalled. Your configuration was preserved."
}

# Unprivileged entry point.
main() {
  local action command completed

  require_command mktemp
  require_command systemctl

  WORK_DIR=$(mktemp -d "${XDG_RUNTIME_DIR:-/tmp}/sunshine-installer.XXXXXX")
  chmod 0700 "${WORK_DIR}"
  select_dialog

  action=$(choose_action) || return 0
  if [[ "${action}" == "uninstall" ]]; then
    require_command pkexec
    uninstall
    return
  fi

  for command in curl jq pkexec sha256sum; do
    require_command "${command}"
  done

  show_installing
  fetch_release || return 1

  if ! run_privileged "${action}" "${RELEASE_FILE}" "${RELEASE_SHA256}" "${RELEASE_TAG}"; then
    close_installing
    show_error "${action^} was canceled or failed."
    return 1
  fi
  if ! activate_service "${action}"; then
    close_installing
    show_error "Sunshine was installed, but its user service could not be started."
    return 1
  fi

  completed="installed"
  [[ "${action}" == "update" ]] && completed="updated"
  close_installing
  show_info "Sunshine ${RELEASE_TAG} was successfully ${completed}."
}

main "$@"
exit $?

# --- Privileged installer payload ---
#!/usr/bin/env bash
set -Eeuo pipefail

# Root-owned paths. Keep every managed path explicit.
readonly ACTION=${1:-}
shift || true
readonly INSTALL_ROOT="/opt/sunshine"
readonly RELEASES="${INSTALL_ROOT}/releases"
readonly CURRENT="${INSTALL_ROOT}/current"
readonly MARKER="${INSTALL_ROOT}/.installed-by-sunshine-desktop"
readonly UDEV_RULE="/etc/udev/rules.d/60-sunshine.rules"
readonly MODULE_CONF="/etc/modules-load.d/60-sunshine.conf"
readonly SERVICE_UNIT="/etc/systemd/user/sunshine.service"
readonly RUNTIME_LINK="/opt/sun"
readonly RUNTIME_TARGET="/opt/sunshine/current/usr"
# Only used to clean up icons copied by older installer versions.
readonly LEGACY_ICON_DIR="/usr/local/share/icons"
readonly LEGACY_STATUS_ICONS=(
  dev.lizardbyte.app.Sunshine-locked.svg
  dev.lizardbyte.app.Sunshine-pausing.svg
  dev.lizardbyte.app.Sunshine-playing.svg
  dev.lizardbyte.app.Sunshine-tray.svg
)

# Transaction state used to roll back a failed install or update.
STAGE=""
COMMIT_STARTED=0
COMMITTED=0
CREATED_INSTALL_ROOT=0
NEW_RELEASE=""
BACKUP_RELEASE=""
ORIGINAL_CURRENT=""
RUNTIME_LINK_EXISTED=0
RUNTIME_LINK_TEMP=""

restore_managed_file() {
  local name=$1
  local target=$2
  if [[ -f "${STAGE}/rollback/${name}" ]]; then
    install -m 0644 -- "${STAGE}/rollback/${name}" "${target}"
  elif [[ -f "${STAGE}/rollback/${name}.missing" ]]; then
    rm -f -- "${target}"
  fi
}

# Restore the previous release and integration files unless commit completed.
cleanup_root() {
  set +e
  if [[ ${COMMIT_STARTED} -eq 1 && ${COMMITTED} -eq 0 ]]; then
    restore_managed_file udev-rule "${UDEV_RULE}"
    restore_managed_file module-conf "${MODULE_CONF}"
    restore_managed_file service-unit "${SERVICE_UNIT}"
    if [[ ${RUNTIME_LINK_EXISTED} -eq 0 ]]; then
      rm -f -- "${RUNTIME_LINK}"
    fi
    if [[ -n "${NEW_RELEASE}" && -e "${NEW_RELEASE}" ]]; then
      rm -rf -- "${NEW_RELEASE}"
    fi
    if [[ -n "${BACKUP_RELEASE}" && -e "${BACKUP_RELEASE}" ]]; then
      mv -- "${BACKUP_RELEASE}" "${NEW_RELEASE}"
    fi
    if [[ -n "${ORIGINAL_CURRENT}" ]]; then
      ln -sfn "${ORIGINAL_CURRENT}" "${INSTALL_ROOT}/.current-rollback"
      mv -Tf -- "${INSTALL_ROOT}/.current-rollback" "${CURRENT}"
    else
      rm -f -- "${CURRENT}"
    fi
  fi
  if [[ ${CREATED_INSTALL_ROOT} -eq 1 && ${COMMITTED} -eq 0 && -d "${INSTALL_ROOT}" ]]; then
    rm -rf -- "${INSTALL_ROOT}"
  fi
  if [[ -n "${RUNTIME_LINK_TEMP}" ]]; then
    rm -f -- "${RUNTIME_LINK_TEMP}"
  fi
  if [[ -n "${STAGE}" && -d "${STAGE}" ]]; then
    rm -rf -- "${STAGE}"
  fi
}
trap cleanup_root EXIT

fail() {
  printf '%s\n' "Sunshine Installer: $*" >&2
  exit 1
}

require_root() {
  [[ ${EUID} -eq 0 ]] || fail "root privileges are required"
}

managed_install_exists() {
  [[ -f "${MARKER}" && $(stat -c '%u' "${MARKER}" 2>/dev/null) == "0" ]]
}

reload_devices() {
  udevadm control --reload-rules >/dev/null 2>&1 || true
  udevadm trigger --property-match=DEVNAME=/dev/uinput >/dev/null 2>&1 || true
  udevadm trigger --property-match=DEVNAME=/dev/uhid >/dev/null 2>&1 || true
  modprobe uinput >/dev/null 2>&1 || true
  modprobe uhid >/dev/null 2>&1 || true
}

# Never replace a short RUNPATH link that this installer does not own.
validate_runtime_link() {
  if [[ -L "${RUNTIME_LINK}" ]]; then
    managed_install_exists || fail "${RUNTIME_LINK} exists but is not managed by this installer"
    [[ $(readlink "${RUNTIME_LINK}") == "${RUNTIME_TARGET}" ]] || fail "${RUNTIME_LINK} is not managed by this installer"
    RUNTIME_LINK_EXISTED=1
  elif [[ -e "${RUNTIME_LINK}" ]]; then
    fail "${RUNTIME_LINK} exists but is not managed by this installer"
  fi
}

# Replace the existing 14-byte RUNPATH in place, without requiring patchelf.
patch_runtime_path() {
  local binary=$1
  local original='$ORIGIN/../lib'
  local replacement='/opt/sun/lib'
  local matches count offset
  matches=$(LC_ALL=C grep -aFbo -- "${original}" "${binary}" || true)
  count=$(printf '%s\n' "${matches}" | sed '/^$/d' | wc -l)
  [[ ${count} -eq 1 ]] || fail "expected exactly one ${original} RUNPATH string, found ${count}"
  offset=${matches%%:*}
  printf '%s\0\0' "${replacement}" | dd of="${binary}" bs=1 seek="${offset}" conv=notrunc status=none
  readelf -d "${binary}" | grep -Fq "Library runpath: [${replacement}]" || fail "could not install the absolute Sunshine RUNPATH"
}

# libva ignores LIBVA_DRIVERS_PATH for executables with file capabilities.
# Replace its Ubuntu default with the host's driver directory in place.
patch_va_driver_path() {
  local library=$1
  local replacement='/usr/lib64/dri'
  local matches count offset original embedded padding
  [[ -f "${library}" ]] || fail "the AppImage payload has no libva.so.2"
  [[ -d "${replacement}" ]] || fail "host VA-API driver directory ${replacement} is missing"
  matches=$(LC_ALL=C grep -aEbo '/usr/lib/(x86_64|aarch64)-linux-gnu/dri' "${library}" || true)
  count=$(printf '%s\n' "${matches}" | sed '/^$/d' | wc -l)
  [[ ${count} -eq 1 ]] || fail "expected exactly one libva driver path, found ${count}"
  offset=${matches%%:*}
  original=${matches#*:}
  IFS= read -r -d '' embedded < <(dd if="${library}" bs=1 skip="${offset}" count="$((${#original} + 1))" status=none) || fail "libva driver path is not null-terminated"
  [[ "${embedded}" == "${original}" ]] || fail "unexpected libva driver path"
  padding=$((${#original} - ${#replacement} + 1))
  [[ ${padding} -gt 0 ]] || fail "replacement libva driver path is too long"
  {
    printf '%s' "${replacement}"
    printf '%*s' "${padding}" '' | tr ' ' '\0'
  } | dd of="${library}" bs=1 seek="${offset}" conv=notrunc status=none
  IFS= read -r -d '' embedded < <(dd if="${library}" bs=1 skip="${offset}" count="$((${#replacement} + 1))" status=none) || fail "could not verify libva driver path"
  [[ "${embedded}" == "${replacement}" ]] || fail "could not patch libva driver path"
}

write_service_unit() {
  local source=$1
  cat >"${source}" <<'UNIT'
[Unit]
Description=Sunshine game streaming host
After=graphical-session.target xdg-desktop-portal.service

[Service]
Type=simple
WorkingDirectory=/opt/sunshine/current
ExecStart=/opt/sunshine/current/usr/bin/sunshine
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=default.target
UNIT
}

backup_managed_file() {
  local source=$1
  local name=$2
  if [[ -f "${source}" ]]; then
    cp -a -- "${source}" "${STAGE}/rollback/${name}"
  else
    : >"${STAGE}/rollback/${name}.missing"
  fi
}

install_release() {
  local appimage=${1:-}
  local expected=${2:-}
  local tag=${3:-}

  # Validate all untrusted arguments before touching system paths.
  [[ -f "${appimage}" ]] || fail "downloaded AppImage is missing"
  [[ "${expected}" =~ ^[A-Fa-f0-9]{64}$ ]] || fail "invalid SHA-256 digest"
  [[ "${tag}" =~ ^[A-Za-z0-9._-]+$ ]] || fail "invalid release tag"
  if [[ -e "${INSTALL_ROOT}" ]] && ! managed_install_exists; then
    fail "${INSTALL_ROOT} exists but is not managed by this installer"
  fi
  validate_runtime_link
  if [[ ! -e "${INSTALL_ROOT}" ]]; then
    CREATED_INSTALL_ROOT=1
  fi

  # Copy and verify the download again after elevation.
  ORIGINAL_CURRENT=$(readlink "${CURRENT}" 2>/dev/null || true)
  STAGE=$(mktemp -d /opt/.sunshine-installer.XXXXXX)
  local root_appimage="${STAGE}/sunshine.AppImage"
  install -m 0700 -- "${appimage}" "${root_appimage}"
  local actual
  actual=$(sha256sum "${root_appimage}")
  actual=${actual%% *}
  [[ "${actual,,}" == "${expected,,}" ]] || fail "root-side SHA-256 verification failed"

  # Extract and validate the complete release before committing anything.
  (cd "${STAGE}" && "${root_appimage}" --appimage-extract >/dev/null)
  local payload="${STAGE}/squashfs-root"
  local binary="${payload}/usr/bin/sunshine"
  local rule="${payload}/usr/share/sunshine/udev/rules.d/60-sunshine.rules"
  local module="${payload}/usr/share/sunshine/modules-load.d/60-sunshine.conf"
  [[ -x "${binary}" ]] || fail "the AppImage payload has no Sunshine executable"
  [[ -f "${rule}" ]] || fail "the AppImage payload has no udev rule"
  [[ -f "${module}" ]] || fail "the AppImage payload has no modules-load configuration"
  # Tray icons are loaded from usr/share/sunshine/web/images in the payload.
  chown -R root:root "${payload}"
  chmod 0755 "${binary}"
  patch_runtime_path "${binary}"
  patch_va_driver_path "${payload}/usr/lib/libva.so.2"
  setcap cap_sys_admin,cap_sys_nice+p "${binary}"

  # Stage host integration files and remember what rollback must restore.
  local staged_rule="${STAGE}/60-sunshine.rules"
  local staged_module="${STAGE}/60-sunshine.conf"
  local staged_unit="${STAGE}/sunshine.service"
  install -m 0644 -- "${rule}" "${staged_rule}"
  install -m 0644 -- "${module}" "${staged_module}"
  write_service_unit "${staged_unit}"
  mkdir -p -- "${STAGE}/rollback"
  backup_managed_file "${UDEV_RULE}" udev-rule
  backup_managed_file "${MODULE_CONF}" module-conf
  backup_managed_file "${SERVICE_UNIT}" service-unit
  mkdir -p -- "${RELEASES}" /etc/udev/rules.d /etc/modules-load.d /etc/systemd/user

  # Install the versioned release and switch to it atomically.
  NEW_RELEASE="${RELEASES}/${tag}"
  BACKUP_RELEASE="${INSTALL_ROOT}/.release-backup-${tag}-$$"
  COMMIT_STARTED=1
  if [[ -e "${NEW_RELEASE}" ]]; then
    mv -- "${NEW_RELEASE}" "${BACKUP_RELEASE}"
  fi
  mv -- "${payload}" "${NEW_RELEASE}"
  install -m 0644 -- "${staged_rule}" "${UDEV_RULE}"
  install -m 0644 -- "${staged_module}" "${MODULE_CONF}"
  install -m 0644 -- "${staged_unit}" "${SERVICE_UNIT}"
  ln -sfn "releases/${tag}" "${INSTALL_ROOT}/.current-new"
  mv -Tf -- "${INSTALL_ROOT}/.current-new" "${CURRENT}"
  RUNTIME_LINK_TEMP="/opt/.sunshine-runtime-new-$$"
  ln -s -- "${RUNTIME_TARGET}" "${RUNTIME_LINK_TEMP}"
  mv -Tf -- "${RUNTIME_LINK_TEMP}" "${RUNTIME_LINK}"
  RUNTIME_LINK_TEMP=""

  # Relabel persistent files, then verify the final executable capabilities.
  if command -v restorecon >/dev/null 2>&1; then
    restorecon -RF "${INSTALL_ROOT}" "${UDEV_RULE}" "${MODULE_CONF}" "${SERVICE_UNIT}" >/dev/null 2>&1 || true
    restorecon -h "${RUNTIME_LINK}" >/dev/null 2>&1 || true
  fi
  setcap cap_sys_admin,cap_sys_nice+p "${CURRENT}/usr/bin/sunshine"
  getcap "${CURRENT}/usr/bin/sunshine" | grep -q 'cap_sys_admin,cap_sys_nice=p' || fail "capabilities were not applied"

  # The marker is written last; after this point the new release is committed.
  local marker_temp="${INSTALL_ROOT}/.marker-new"
  printf 'version=%s\nsha256=%s\n' "${tag}" "${expected,,}" >"${marker_temp}"
  chmod 0644 "${marker_temp}"
  mv -f -- "${marker_temp}" "${MARKER}"
  COMMITTED=1
  rm -rf -- "${BACKUP_RELEASE}"

  # Keep only the active versioned release.
  local old_release
  while IFS= read -r -d '' old_release; do
    [[ "${old_release}" == "${NEW_RELEASE}" ]] || rm -rf -- "${old_release}"
  done < <(find "${RELEASES}" -mindepth 1 -maxdepth 1 -type d -print0)
  reload_devices
}

uninstall_release() {
  managed_install_exists || fail "no installer-managed Sunshine installation was found"
  validate_runtime_link
  rm -f -- "${SERVICE_UNIT}" "${UDEV_RULE}" "${MODULE_CONF}"
  rm -f -- "${RUNTIME_LINK}"
  local icon
  for icon in "${LEGACY_STATUS_ICONS[@]}"; do
    rm -f -- "${LEGACY_ICON_DIR}/${icon}"
  done
  rm -rf -- "${INSTALL_ROOT}"
  reload_devices
}

require_root
case "${ACTION}" in
  install | update) install_release "$@" ;;
  uninstall)
    [[ $# -eq 0 ]] || fail "uninstall takes no arguments"
    uninstall_release
    ;;
  *) fail "unsupported action: ${ACTION}" ;;
esac
