#!/usr/bin/env bash
#
# Lienox one-command installer (Linux & macOS)
#
#   curl -fsSL https://get.lienox.com | bash
#
# Downloads the latest release from GitHub, verifies its SHA-256 checksum
# against the published SHA256SUMS file, and installs it.
#
# To remove a Linux install (app data under ~/.config/Lienox is NEVER touched):
#   curl -fsSL https://get.lienox.com | bash -s -- --uninstall
#
# Asset naming contract (must match the release builder exactly):
#   Linux : Lienox-${version}.AppImage   (x86-64 only — electron-builder.yml has no arm64 target)
#   macOS : Lienox-${version}-arm64.dmg  (Apple Silicon only — no Intel build exists)
#
set -euo pipefail

# ── Configuration ───────────────────────────────────────────────────────────
REPO="DiegoGaxi/lienox-releases"
API_URL="https://api.github.com/repos/${REPO}/releases/latest"

# ── Pretty output ───────────────────────────────────────────────────────────
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  BOLD=$'\033[1m'; DIM=$'\033[2m'; RESET=$'\033[0m'
  RED=$'\033[31m'; GREEN=$'\033[32m'; YELLOW=$'\033[33m'; CYAN=$'\033[36m'
else
  BOLD=""; DIM=""; RESET=""; RED=""; GREEN=""; YELLOW=""; CYAN=""
fi

info()  { printf '%s\n' "${CYAN}::${RESET} $*"; }
ok()    { printf '%s\n' "${GREEN}✓${RESET} $*"; }
warn()  { printf '%s\n' "${YELLOW}!${RESET} $*" >&2; }
err()   { printf '%s\n' "${RED}✗ $*${RESET}" >&2; }
die()   { err "$@"; exit 1; }

banner() {
  printf '%s\n' "${BOLD}${CYAN}"
  printf '%s\n' "   _                    _    ____ _           _       "
  printf '%s\n' "  /_\\  __ _ ___ _ _| |_ / ___| |__   __ _(_)_ _  "
  printf '%s\n' " / _ \\/ _\` / -_) ' \\  _| (__| ' \\ / _\` | | ' \\ "
  printf '%s\n' "/_/ \\_\\__, \\___|_||_\\__|\\___|_||_\\__,_|_|_||_|"
  printf '%s\n' "      |___/                                          "
  printf '%s\n' "${RESET}${DIM}        one-command installer${RESET}"
  printf '\n'
}

# ── Dependency helpers ──────────────────────────────────────────────────────
have() { command -v "$1" >/dev/null 2>&1; }

require() {
  have "$1" || die "Required command '$1' is not installed."
}

# Pick an available HTTP downloader.
# A snap-packaged curl (/snap/bin/curl — the FIRST thing Ubuntu's command-not-found suggests when
# curl is missing) is strictly confined: it has its own private /tmp and cannot write to the real
# one, so `curl -o /tmp/tmp.X/Lienox.AppImage` fails and the install dies before the menu entry is
# created. Piping this script through it is fine (stdout), downloading files with it is not.
# Prefer wget in that case (Ubuntu ships it); with no wget, keep snap curl but stage downloads
# under $HOME, which its `home` plug CAN write (see make_tmp).
DOWNLOADER=""
SNAP_CURL=0
case "$(command -v curl 2>/dev/null)" in /snap/*) SNAP_CURL=1 ;; esac
if have curl && { [ "$SNAP_CURL" -eq 0 ] || ! have wget; }; then
  DOWNLOADER="curl"
elif have wget; then
  DOWNLOADER="wget"
  SNAP_CURL=0
else
  die "Need either 'curl' or 'wget' to download files."
fi

# make_tmp -> a fresh temp dir the downloader can write into.
make_tmp() {
  if [ "$SNAP_CURL" -eq 1 ]; then
    mktemp -d "${HOME}/lienox-install.XXXXXX"
  else
    mktemp -d
  fi
}

# Is the FUSE2 runtime (libfuse.so.2) available? AppImages self-mount through it.
# Two traps the old one-liner `ldconfig -p | grep -q …` fell into:
#   - under `set -o pipefail`, grep -q exits on the first match, ldconfig takes SIGPIPE and the
#     pipeline reports FAILURE even though the library is there (measured: ~1 run in 5) — which
#     then fired a needless `sudo apt-get` and a password prompt.
#   - ldconfig lives in /sbin, which is not on a regular user's PATH on Debian.
have_fuse2() {
  local ld libs
  ld="$(command -v ldconfig 2>/dev/null || true)"
  [ -n "$ld" ] || ld=/sbin/ldconfig
  libs="$("$ld" -p 2>/dev/null || true)"
  case "$libs" in *libfuse.so.2*) return 0 ;; esac
  return 1
}

# fetch <url> -> stdout
fetch() {
  if [ "$DOWNLOADER" = "curl" ]; then
    curl -fsSL "$1"
  else
    wget -qO- "$1"
  fi
}

# download <url> <dest>
download() {
  local url="$1" dest="$2"
  info "Downloading $(basename "$dest") ..."
  if [ "$DOWNLOADER" = "curl" ]; then
    curl -fSL --progress-bar "$url" -o "$dest"
  else
    wget -q --show-progress -O "$dest" "$url"
  fi
}

# ── Platform detection ──────────────────────────────────────────────────────
detect_os() {
  case "$(uname -s)" in
    Linux*)  echo "linux"  ;;
    Darwin*) echo "darwin" ;;
    *) die "Unsupported operating system: $(uname -s)" ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64)        echo "x86_64" ;;
    arm64|aarch64)       echo "arm64"  ;;
    *) die "Unsupported architecture: $(uname -m)" ;;
  esac
}

# ── GitHub release metadata ─────────────────────────────────────────────────
RELEASE_JSON=""
load_release() {
  info "Querying latest release from ${REPO} ..."
  RELEASE_JSON="$(fetch "$API_URL")" \
    || die "Could not reach the GitHub release API."
  [ -n "$RELEASE_JSON" ] || die "Empty response from GitHub release API."
}

# release_tag -> the tag name, e.g. v1.2.3
release_tag() {
  if have jq; then
    printf '%s' "$RELEASE_JSON" | jq -r '.tag_name // empty'
  else
    printf '%s' "$RELEASE_JSON" \
      | grep -m1 '"tag_name"' \
      | sed -E 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/'
  fi
}

# asset_url <asset-name> -> browser_download_url for an exact asset name
asset_url() {
  local name="$1"
  if have jq; then
    printf '%s' "$RELEASE_JSON" \
      | jq -r --arg n "$name" \
        '.assets[] | select(.name == $n) | .browser_download_url' \
      | head -n1
  else
    # Walk the JSON looking for the browser_download_url whose path ends in
    # exactly the asset name. Newlines are inserted before each URL key so
    # grep can isolate one candidate per line.
    printf '%s' "$RELEASE_JSON" \
      | tr ',' '\n' \
      | grep '"browser_download_url"' \
      | sed -E 's/.*"browser_download_url"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/' \
      | grep -E "/${name}$" \
      | head -n1
  fi
}

# ── Checksum verification ───────────────────────────────────────────────────
# verify_checksum <file> <asset-name> <sha256sums-file>
# Returns 0 if verified, 1 if mismatch, 2 if no entry / cannot verify.
verify_checksum() {
  local file="$1" name="$2" sums="$3"
  local expected actual sha_cmd

  expected="$(grep -E "[[:space:]]\*?${name}\$" "$sums" 2>/dev/null \
              | head -n1 | awk '{print $1}')"
  [ -n "$expected" ] || return 2

  if have sha256sum; then
    sha_cmd="sha256sum"
    actual="$(sha256sum "$file" | awk '{print $1}')"
  elif have shasum; then
    sha_cmd="shasum -a 256"
    actual="$(shasum -a 256 "$file" | awk '{print $1}')"
  else
    return 2
  fi

  if [ "$expected" = "$actual" ]; then
    return 0
  fi
  return 1
}

# ── Linux paths (shared by install and uninstall) ───────────────────────────
linux_desktop_file() { printf '%s' "${HOME}/.local/share/applications/lienox.desktop"; }
linux_icon_file()    { printf '%s' "${HOME}/.local/share/icons/hicolor/1024x1024/apps/lienox.png"; }

# ── Does this kernel let Chromium use its namespace sandbox? ────────────────
# Electron's sandbox needs unprivileged user namespaces. Inside an AppImage the bundled
# chrome-sandbox helper can never be SUID (the image is mounted nosuid, and so is most /tmp for
# the extract-and-run path), so the namespace sandbox is the ONLY one available — and when the
# kernel forbids it, Electron does not degrade, it ABORTS before showing a window:
#   "The SUID sandbox helper binary was found, but is not configured correctly."
# Ubuntu 24.04+ ships that restriction ON by default via AppArmor. Detecting it here and adding
# --no-sandbox to the launcher is the difference between an app that opens and one that doesn't.
# The check is BEHAVIOURAL — actually try to create a user namespace — and only falls back to
# reading sysctls when there is no tool to try it with. Reading
# /proc/sys/kernel/apparmor_restrict_unprivileged_userns alone is NOT good enough and would be
# actively harmful: on a stock Ubuntu 24.04 desktop that file reads 1 while `unshare --user true`
# still succeeds (the restriction transitions unconfined binaries into an implicit profile rather
# than denying outright). Trusting the sysctl there would strip the Chromium sandbox — a real
# security downgrade — on machines that never needed it. So: only add --no-sandbox when creating a
# namespace demonstrably FAILS.
#
# Returns 0 when --no-sandbox is required.
userns_restricted() {
  local f v
  # Hardened kernels / containers: a zero quota means no namespace can be created at all.
  # Cheap, unambiguous, and true regardless of AppArmor.
  f=/proc/sys/user/max_user_namespaces
  if [ -r "$f" ] && v="$(cat "$f" 2>/dev/null)" && [ "$v" = "0" ]; then return 0; fi
  # Debian/Ubuntu's older toggle: 0 = unprivileged userns disabled outright (no profile dance).
  f=/proc/sys/kernel/unprivileged_userns_clone
  if [ -r "$f" ] && v="$(cat "$f" 2>/dev/null)" && [ "$v" = "0" ]; then return 0; fi
  # The real test.
  if have unshare; then
    unshare --user true >/dev/null 2>&1 && return 1  # it works → keep the sandbox
    return 0
  fi
  # No unshare to test with — assume the sandbox works rather than silently disabling it.
  return 1
}

# ── Install: Linux ──────────────────────────────────────────────────────────
install_linux() {
  local version="$1" arch="$2"
  # x86-64 only. electron-builder.yml declares `AppImage arch: x64` and nothing else, and the
  # asset name carries no architecture — so on an ARM machine the old code happily downloaded an
  # x86-64 image, reported success, and left the user with a launcher that dies on "cannot execute
  # binary file". Say it plainly instead, the way the macOS/Intel branch already does.
  case "$arch" in
    x86_64) : ;;
    *) die "Lienox for Linux is currently x86-64 only.
This machine reports '${arch}' and there is no ARM build — the release pipeline publishes a single
x64 AppImage. Lienox also runs on macOS (Apple Silicon) and Windows." ;;
  esac
  local appimage="Lienox-${version}.AppImage"
  local url
  url="$(asset_url "$appimage")"

  [ -n "$url" ] || die "No AppImage named '${appimage}' in release ${version}.
Available assets did not include the expected Linux build."

  local tmp
  tmp="$(make_tmp)"
  # Guard with ${tmp:-}: a RETURN trap set in a function persists and also fires
  # on main()'s return (where this local is out of scope) → under `set -u` that
  # raised "tmp: unbound variable" after a successful install. The :- makes it safe.
  trap 'rm -rf "${tmp:-}"' RETURN
  local out="${tmp}/${appimage}"

  download "$url" "$out"

  # Verify against the per-platform SHA256SUMS file (best-effort, non-fatal if absent).
  local sums_url sums_file
  sums_url="$(asset_url "SHA256SUMS-linux.txt")"
  if [ -n "$sums_url" ]; then
    sums_file="${tmp}/SHA256SUMS"
    if fetch "$sums_url" > "$sums_file" 2>/dev/null; then
      if verify_checksum "$out" "$appimage" "$sums_file"; then
        ok "Checksum verified."
      else
        case $? in
          1) die "Checksum MISMATCH for ${appimage}. Aborting for safety." ;;
          *) warn "Could not verify checksum (no entry / no tool). Continuing." ;;
        esac
      fi
    else
      warn "Could not download SHA256SUMS. Skipping verification."
    fi
  else
    warn "Release has no SHA256SUMS asset. Skipping verification."
  fi

  # Choose an install location: prefer a writable ~/.local/bin (no sudo),
  # fall back to /usr/local/bin via sudo if the home directory is unusable.
  local bindir target used_sudo=0
  bindir="${HOME}/.local/bin"
  if ! mkdir -p "$bindir" 2>/dev/null; then
    if have sudo; then
      bindir="/usr/local/bin"
      sudo mkdir -p "$bindir"
      used_sudo=1
    else
      die "Cannot create ${HOME}/.local/bin and sudo is unavailable."
    fi
  fi
  target="${bindir}/Lienox.AppImage"

  if [ "$used_sudo" -eq 1 ]; then
    sudo install -m 0755 "$out" "$target"
  else
    install -m 0755 "$out" "$target" 2>/dev/null || {
      cp "$out" "$target" && chmod +x "$target"
    }
  fi
  ok "Installed to ${BOLD}${target}${RESET}"

  # AppImages self-mount via FUSE2 (libfuse.so.2). Many modern desktops (e.g.
  # Ubuntu 24.04) don't ship it, and without it the app fails at launch with
  # "dlopen(): error loading libfuse.so.2" and never starts. Ensure it's present;
  # if we can't install it, fall back to extraction mode so the app still runs.
  local exec_args=""
  if ! have_fuse2; then
    warn "AppImage runtime FUSE2 (libfuse.so.2) is not installed."
    if have apt-get && have sudo; then
      info "Installing libfuse2 (needs sudo) ..."
      sudo apt-get update -qq 2>/dev/null || true
      sudo apt-get install -y libfuse2t64 2>/dev/null || sudo apt-get install -y libfuse2 2>/dev/null || true
    elif have dnf && have sudo; then
      sudo dnf install -y fuse-libs 2>/dev/null || true
    elif have pacman && have sudo; then
      sudo pacman -S --noconfirm fuse2 2>/dev/null || true
    fi
    if have_fuse2; then
      ok "FUSE2 installed."
    else
      warn "Could not install FUSE2 — using extraction mode (slightly slower first launch)."
      exec_args=" --appimage-extract-and-run"
    fi
  fi

  # Chromium sandbox: see userns_restricted(). Without this the app aborts at startup on a
  # stock Ubuntu 24.04 and the user has no way to know why — the failure is printed to a
  # terminal they never opened, because they launched it from the app menu.
  if userns_restricted; then
    warn "This kernel restricts unprivileged user namespaces (Ubuntu 24.04+ does by default)."
    warn "Launching with --no-sandbox — an AppImage cannot use the SUID sandbox anyway."
    exec_args="${exec_args} --no-sandbox"
  fi

  # Install the app icon into the user's hicolor theme. Without this the desktop
  # entry's Icon= name resolves to nothing and launchers fall back to a generic
  # gear. The icon ships INSIDE the AppImage, so pull it out — `--appimage-extract`
  # takes a glob and unpacks only the match (a few hundred KB, not the whole 250MB
  # image) and needs no FUSE.
  local icon_name="lienox"
  local icon_dir
  icon_dir="$(dirname "$(linux_icon_file)")"
  local icon_ref="$icon_name"   # themed-name fallback if extraction fails
  local icon_tmp extracted
  icon_tmp="$(make_tmp)"
  if ( cd "$icon_tmp" && "$target" --appimage-extract "usr/share/icons/hicolor/*/apps/*.png" ) >/dev/null 2>&1; then
    # `|| true`: under `set -o pipefail`, find can take SIGPIPE once head closes
    # the pipe, and the failing substitution would abort the install via `set -e`.
    extracted="$(find "${icon_tmp}/squashfs-root" -type f -name '*.png' 2>/dev/null | head -n 1 || true)"
    if [ -n "${extracted:-}" ] && mkdir -p "$icon_dir" 2>/dev/null &&
       cp "$extracted" "${icon_dir}/${icon_name}.png" 2>/dev/null; then
      chmod 0644 "${icon_dir}/${icon_name}.png" 2>/dev/null || true
      # Absolute path (allowed by the desktop-entry spec) renders immediately even
      # where the icon cache is stale; the hicolor install above additionally makes
      # the bare `lienox` name resolve for window/dock matching.
      icon_ref="${icon_dir}/${icon_name}.png"
      if have gtk-update-icon-cache; then
        gtk-update-icon-cache -f -t "${HOME}/.local/share/icons/hicolor" >/dev/null 2>&1 || true
      fi
      ok "Installed app icon."
    fi
  fi
  rm -rf "$icon_tmp"
  # Plain `if`, not `[ … ] && warn`: on the success path that test is false, the
  # compound returns 1, and `set -e` would abort the install right after we won.
  if [ "$icon_ref" = "$icon_name" ]; then
    warn "Could not extract the app icon — the launcher may show a generic one."
  fi

  # Desktop control (agents driving the mouse/keyboard/screen) needs host tools no stock distro
  # ships — ydotool/xdotool, wl-clipboard, flameshot — plus write access to /dev/uinput. The app
  # would otherwise ask for them in a dialog on first launch; we're already in a terminal that may
  # have asked for the password (libfuse2), so do it here. The script ships INSIDE the AppImage
  # (single source: frontend-v2/scripts/setup-linux-desktop.sh) — pulled out the same way as the
  # icon. Never fatal: a release without it, or a declined password, just leaves it to the app.
  setup_desktop_control "$target"

  # Create a .desktop entry for menu launchers.
  local desktop apps_dir
  desktop="$(linux_desktop_file)"
  apps_dir="$(dirname "$desktop")"
  mkdir -p "$apps_dir"
  cat > "$desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Lienox
Comment=Lienox desktop app
Exec=${target}${exec_args} %U
Icon=${icon_ref}
Terminal=false
Categories=Development;Utility;
StartupWMClass=Lienox
EOF
  chmod 0644 "$desktop"
  update-desktop-database "$apps_dir" >/dev/null 2>&1 || true
  ok "Created desktop entry: ${desktop}"

  printf '\n'
  ok "${BOLD}Lienox ${version} installed!${RESET}"
  info "Launch it from your app menu, or run:"
  printf '    %s\n' "${BOLD}${target}${exec_args}${RESET}"
  case ":${PATH}:" in
    *":${bindir}:"*) : ;;
    *) warn "${bindir} is not on your PATH. Add it with:"
       printf '    %s\n' "export PATH=\"${bindir}:\$PATH\"" ;;
  esac
}

# setup_desktop_control <appimage> — run the bundled one-time root setup for desktop control.
setup_desktop_control() {
  local appimage="$1" tmp script
  have sudo || { warn "sudo unavailable — Lienox will offer the desktop-control setup on first launch."; return 0; }
  tmp="$(make_tmp)"
  script="${tmp}/squashfs-root/resources/services/setup-linux-desktop.sh"
  if ( cd "$tmp" && "$appimage" --appimage-extract "resources/services/setup-linux-desktop.sh" ) >/dev/null 2>&1 &&
     [ -f "$script" ]; then
    info "Setting up desktop control (mouse/keyboard/screen tools — needs sudo) ..."
    if sudo bash "$script"; then
      ok "Desktop control ready."
    else
      warn "Desktop-control setup incomplete — Lienox will offer it again on first launch."
    fi
  fi
  rm -rf "$tmp"
  return 0
}

# ── Install: macOS ──────────────────────────────────────────────────────────
install_macos() {
  local version="$1" arch="$2"
  local dmg_arch
  case "$arch" in
    # Apple Silicon only — the release pipeline builds a single arm64 .dmg (the Intel
    # runner is retired upstream). Say so plainly: the old code just looked for a
    # Lienox-<v>-x64.dmg that has never existed and died on "No disk image named…",
    # which reads like a broken release rather than an unsupported machine.
    x86_64) die "Lienox for macOS currently requires Apple Silicon (M1 or newer).
This Mac is Intel (x86_64) and there is no Intel build — Rosetta cannot help, the
app bundles native arm64 binaries. Lienox also runs on Linux and Windows." ;;
    arm64)  dmg_arch="arm64" ;;
    *) die "Unsupported macOS architecture: $arch" ;;
  esac

  local dmg="Lienox-${version}-${dmg_arch}.dmg"
  local url
  url="$(asset_url "$dmg")"

  [ -n "$url" ] || die "No disk image named '${dmg}' in release ${version}.
Available assets did not include the expected macOS (${dmg_arch}) build."

  local tmp
  tmp="$(make_tmp)"
  trap 'rm -rf "${tmp:-}"' RETURN
  local out="${tmp}/${dmg}"

  download "$url" "$out"

  # Verify against the per-platform SHA256SUMS file (mac builds are arm64-only).
  local sums_url sums_file
  sums_url="$(asset_url "SHA256SUMS-mac-arm64.txt")"
  if [ -n "$sums_url" ]; then
    sums_file="${tmp}/SHA256SUMS"
    if fetch "$sums_url" > "$sums_file" 2>/dev/null; then
      if verify_checksum "$out" "$dmg" "$sums_file"; then
        ok "Checksum verified."
      else
        case $? in
          1) die "Checksum MISMATCH for ${dmg}. Aborting for safety." ;;
          *) warn "Could not verify checksum (no entry / no tool). Continuing." ;;
        esac
      fi
    else
      warn "Could not download SHA256SUMS. Skipping verification."
    fi
  else
    warn "Release has no SHA256SUMS asset. Skipping verification."
  fi

  # Mount the DMG, copy the app, then detach.
  info "Mounting disk image ..."
  local mountpoint
  mountpoint="$(mktemp -d "${tmp}/mnt.XXXXXX")"
  hdiutil attach "$out" -nobrowse -quiet -mountpoint "$mountpoint" \
    || die "Failed to mount ${dmg}."

  # shellcheck disable=SC2064
  trap "hdiutil detach '$mountpoint' -quiet >/dev/null 2>&1 || true; rm -rf '$tmp'" RETURN

  local app_src
  app_src="$(find "$mountpoint" -maxdepth 1 -name '*.app' -print -quit)"
  [ -n "$app_src" ] || die "No .app bundle found inside ${dmg}."

  local app_name dest
  app_name="$(basename "$app_src")"
  dest="/Applications/${app_name}"

  info "Installing ${app_name} to /Applications ..."
  rm -rf "$dest" 2>/dev/null || sudo rm -rf "$dest" 2>/dev/null || true
  if cp -R "$app_src" "$dest" 2>/dev/null; then
    :
  else
    warn "Need elevated permissions to write to /Applications."
    sudo cp -R "$app_src" "$dest" || die "Failed to copy app to /Applications."
  fi

  info "Unmounting disk image ..."
  hdiutil detach "$mountpoint" -quiet >/dev/null 2>&1 || true

  # Strip the Gatekeeper quarantine flag — these builds are UNSIGNED.
  info "Removing Gatekeeper quarantine (build is unsigned) ..."
  xattr -dr com.apple.quarantine "$dest" 2>/dev/null \
    || sudo xattr -dr com.apple.quarantine "$dest" 2>/dev/null \
    || warn "Could not clear quarantine; you may need to allow the app in System Settings → Privacy & Security."

  printf '\n'
  ok "${BOLD}Lienox ${version} installed!${RESET}"
  info "Open it from /Applications or run:"
  printf '    %s\n' "${BOLD}open \"${dest}\"${RESET}"
  printf '\n'
  warn "${BOLD}Note:${RESET} this build is ${BOLD}unsigned${RESET}. If macOS still blocks it, open"
  warn "System Settings → Privacy & Security and click ${BOLD}Open Anyway${RESET} under the"
  warn "message about Lienox. (The old right-click → Open shortcut was removed in macOS 15.)"
}

# ── Uninstall ───────────────────────────────────────────────────────────────
# Removes only what THIS script put on disk. User data (the database, API keys, projects, logs —
# ~/.config/Lienox on Linux, ~/Library/Application Support/Lienox on macOS) is deliberately left
# alone: an uninstall must never be the thing that destroys someone's work, and reinstalling on
# top of it is the normal recovery path.
uninstall() {
  local os removed=0
  os="$(detect_os)"
  if [ "$os" = "linux" ]; then
    local target desktop icon
    target="${HOME}/.local/bin/Lienox.AppImage"
    desktop="$(linux_desktop_file)"
    icon="$(linux_icon_file)"
    for f in "$target" "$desktop" "$icon"; do
      if [ -e "$f" ]; then rm -f "$f" && ok "Removed ${f}" && removed=1; fi
    done
    # A system-wide copy exists only when $HOME was unusable at install time (see install_linux).
    if [ -e /usr/local/bin/Lienox.AppImage ] && have sudo; then
      sudo rm -f /usr/local/bin/Lienox.AppImage && ok "Removed /usr/local/bin/Lienox.AppImage" && removed=1
    fi
    update-desktop-database "$(dirname "$desktop")" >/dev/null 2>&1 || true
    if have gtk-update-icon-cache; then
      gtk-update-icon-cache -f -t "${HOME}/.local/share/icons/hicolor" >/dev/null 2>&1 || true
    fi
  else
    local dest="/Applications/Lienox.app"
    if [ -d "$dest" ]; then
      rm -rf "$dest" 2>/dev/null || sudo rm -rf "$dest" || die "Could not remove ${dest}."
      ok "Removed ${dest}"
      removed=1
    fi
  fi
  if [ "$removed" -eq 0 ]; then
    warn "Nothing to remove — Lienox does not appear to be installed by this script."
  else
    printf '\n'
    ok "${BOLD}Lienox uninstalled.${RESET}"
    info "Your data was NOT deleted. To remove it too:"
    if [ "$os" = "linux" ]; then
      printf '    %s\n' "rm -rf ~/.config/Lienox"
    else
      printf '    %s\n' "rm -rf ~/Library/Application\\ Support/Lienox"
    fi
  fi
}

# ── Refuse `sudo` on Linux ──────────────────────────────────────────────────
# Everything on Linux is PER-USER (~/.local/bin, ~/.local/share/applications). Under sudo, Ubuntu
# resets HOME to /root, so the install "succeeds" into root's home: the user's app menu never shows
# Lienox and an uninstall without sudo finds nothing. People reach for sudo precisely when the
# script asks for a password (libfuse2), so say it plainly instead of installing for the wrong user.
# A genuine root login (no SUDO_USER) is left alone — that IS the user whose menu we are filling.
refuse_sudo_on_linux() {
  [ "$(uname -s)" = "Linux" ] || return 0
  [ "$(id -u)" -eq 0 ] || return 0
  if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ]; then
    die "Don't run the installer with sudo.
Lienox installs for your user only (it would land in /root and never show up in your app menu).
Run it as yourself — it asks for your password on its own when system packages are needed:
    curl -fsSL https://get.lienox.com/install.sh | bash"
  fi
  warn "Running as root: Lienox will be installed for the root account only."
}

# ── Main ────────────────────────────────────────────────────────────────────
main() {
  banner
  refuse_sudo_on_linux

  case "${1:-}" in
    --uninstall|-u|uninstall) uninstall; return 0 ;;
    --help|-h) info "Usage: install.sh [--uninstall]"; return 0 ;;
    '') : ;;
    *) die "Unknown option: $1 (try --help)" ;;
  esac

  local os arch version
  os="$(detect_os)"
  arch="$(detect_arch)"
  info "Detected platform: ${BOLD}${os}/${arch}${RESET}"

  load_release
  version="$(release_tag)"
  [ -n "$version" ] || die "Could not determine the latest release tag."
  # The release TAG is v-prefixed (e.g. v2.0.9) but the installer ASSET names use
  # the bare version (Lienox-2.0.9.AppImage). Strip the leading 'v' so the
  # asset lookups below match.
  version="${version#v}"
  info "Latest release: ${BOLD}v${version}${RESET}"
  printf '\n'

  case "$os" in
    linux)  install_linux  "$version" "$arch" ;;
    darwin) install_macos  "$version" "$arch" ;;
    *) die "Unsupported OS: $os" ;;
  esac
}

main "$@"
