#!/bin/sh
# nibspark 0.21.0 installer for Linux.
#
# Installs the AppImage for the current user (no root needed) and adds a
# desktop entry, so nibspark shows up in the app launcher. nibspark supports
# auto-updating, and the desktop entry keeps working across updates.
#
# Usage:
#   curl -fsSL https://nibspark.app/install.sh | sh
#   curl -fsSL https://nibspark.app/install.sh | sh -s -- --uninstall
#
# Installed files (removed by --uninstall):
#   ~/.local/share/nibspark/nibspark-<arch>.AppImage
#   ~/.local/share/applications/nibspark.desktop
#   ~/.local/share/icons/hicolor/512x512/apps/nibspark.png
#   ~/.local/bin/nibspark  (symlink to the AppImage)
#
# The download is verified against the release's SHA-256, and against
# nibspark's minisign signature when minisign is installed. Re-running the
# script reinstalls the latest version.
set -eu

VERSION='0.21.0'
# Download URL and SHA-256 per architecture. Empty when the release has no
# signed AppImage for it.
X86_64_URL='https://github.com/tulios/nibspark-releases/releases/download/v0.21.0/nibspark-x86_64.AppImage'
X86_64_SHA256='43d8cd8f0e85adc2ae59e5ffa5018454d83b5e682fc0e3b50b9fc8872e987d29'
AARCH64_URL='https://github.com/tulios/nibspark-releases/releases/download/v0.21.0/nibspark-aarch64.AppImage'
AARCH64_SHA256='bf70b05ba0b3f3d6f7c2d7f262b5390282ea4c70d00337ea332e13c9ec3b8501'
# Public key for release signatures.
UPDATE_KEY='RWRQhl2FycN+wRBO0gCHXNqSA8gArG4quBbSyUvtYxQmQa7R7eUUi1Ll'
# The oldest glibc nibspark runs on: Ubuntu 22.04's, which it's built on.
MIN_GLIBC=2.35

data="${XDG_DATA_HOME:-$HOME/.local/share}"
dir="$data/nibspark"
entry="$data/applications/nibspark.desktop"
icon="$data/icons/hicolor/512x512/apps/nibspark.png"
link="$HOME/.local/bin/nibspark"

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

# True if $1 is a symlink this script created, so it's safe to replace or
# remove.
ours() { [ -L "$1" ] && case "$(readlink "$1")" in "$dir"/*.AppImage) true ;; *) false ;; esac; }

# Refreshes the desktop and icon caches, where the system has them.
refresh() {
  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database -q "$data/applications" 2>/dev/null || true
  fi
  if command -v gtk-update-icon-cache >/dev/null 2>&1 && [ -f "$data/icons/hicolor/index.theme" ]; then
    gtk-update-icon-cache -q "$data/icons/hicolor" 2>/dev/null || true
  fi
}

# The nib and its spark, in the logo's colors when the output is a
# terminal that takes them (not with NO_COLOR set).
banner() {
  r="" b="" dim="" pink="" gold="" v1="" v2="" v3="" v4="" v5=""
  if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then
    e="$(printf '\033')"
    r="$e[0m" b="$e[1m" dim="$e[2m"
    pink="$e[38;2;236;72;153m" gold="$e[38;2;250;204;21m"
    v1="$e[38;2;196;181;253m" v2="$e[38;2;167;139;250m" v3="$e[38;2;139;120;240m"
    v4="$e[38;2;109;100;226m" v5="$e[38;2;91;84;200m"
  fi
  say ""
  say "            ${gold}✦${r}"
  say "        ${gold}·${r}   ${pink}▲${r}   ${gold}·${r}"
  say "           ${v1}▟█▙${r}"
  say "          ${v1}▟█│█▙${r}        ${b}n i b s p a r k${r}"
  say "         ${v2}▟██│██▙${r}       ${dim}Plain Markdown, beautifully written${r}"
  say "         ${v3}███●███${r}"
  say "         ${v3}▜█████▛${r}"
  say "         ${v4}▗▄▄▄▄▄▖${r}"
  say "         ${v5}▐█████▌${r}"
  say ""
}

uninstall() {
  rm -f "$dir"/nibspark-*.AppImage "$entry" "$icon"
  rm -rf "$dir/.nibspark-update"  # a pending auto-update, if any
  rmdir "$dir" 2>/dev/null || true
  if ours "$link"; then rm -f "$link"; fi
  refresh
  say "nibspark is uninstalled. Your notes and settings are left as they are."
}

case "${1:-}" in
  --uninstall) uninstall; exit 0 ;;
  "") ;;
  -h | --help) say "Installs nibspark $VERSION for you, or with --uninstall, removes it."; exit 0 ;;
  *) fail "unknown option: $1" ;;
esac

banner

[ "$(uname -s)" = Linux ] || fail "this installs the Linux app; for $(uname -s), see https://nibspark.app/#download"
[ "$(id -u)" != 0 ] || fail "run this as yourself, not root: it installs into your home folder"

arch="$(uname -m)"
case "$arch" in
  x86_64 | amd64) arch=x86_64 url="$X86_64_URL" sha256="$X86_64_SHA256" ;;
  aarch64 | arm64) arch=aarch64 url="$AARCH64_URL" sha256="$AARCH64_SHA256" ;;
  *) url="" sha256="" ;;
esac
[ -n "$url" ] || fail "there's no nibspark $VERSION for $arch yet; see https://nibspark.app/#download"

# nibspark is built against glibc 2.35 (Ubuntu 22.04): an older glibc, or
# none (musl, as on Alpine), can't start it, so say so before downloading.
# The Flatpak and the snap bring their own.
if command -v getconf >/dev/null 2>&1; then
  glibc="$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{ print $2 }')" || glibc=""
  [ -n "$glibc" ] || fail "nibspark needs glibc, which this system doesn't use; see https://nibspark.app/#download for the Flatpak or the snap"
  echo "$glibc" | awk -F. -v want="$MIN_GLIBC" '{ split(want, w, "."); exit !($1 > w[1] || ($1 == w[1] && $2 >= w[2])) }' \
    || fail "nibspark needs glibc $MIN_GLIBC or newer, and this system has $glibc; see https://nibspark.app/#download for the Flatpak or the snap"
fi

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fL --progress-bar -o "$2" "$1"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -q --show-progress -O "$2" "$1"; }
else
  fail "curl or wget is needed to download nibspark"
fi

work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT INT TERM
name="nibspark-$arch.AppImage"
download="$work/$name"

say "Downloading nibspark $VERSION for $arch"
fetch "$url" "$download" || fail "couldn't download $url"

if [ -n "$sha256" ]; then
  if command -v sha256sum >/dev/null 2>&1; then
    got="$(sha256sum "$download" | cut -d ' ' -f 1)"
  else
    got="$(shasum -a 256 "$download" | cut -d ' ' -f 1)"
  fi
  [ "$got" = "$sha256" ] || fail "the download doesn't match the release's SHA-256: nothing was installed"
fi

# Verify the signature, and that its trusted comment names this version
# and file (the same check the auto-updater does).
if command -v minisign >/dev/null 2>&1; then
  fetch "$url.minisig" "$download.minisig" 2>/dev/null || fail "couldn't download the signature: nothing was installed"
  minisign -Vm "$download" -P "$UPDATE_KEY" -x "$download.minisig" -q >/dev/null 2>&1 \
    || fail "the download isn't signed by nibspark: nothing was installed"
  grep -qx "trusted comment: nibspark $VERSION $name" "$download.minisig" \
    || fail "the signature isn't for nibspark $VERSION's $name: nothing was installed"
  say "Signature checked"
fi
chmod 755 "$download"

# Extract the desktop entry and icon from the AppImage. This doesn't run
# the app and doesn't need FUSE.
(cd "$work" && "$download" --appimage-extract 'usr/share/*' >/dev/null 2>&1) \
  || fail "couldn't open the AppImage"
share="$work/squashfs-root/usr/share"
[ -f "$share/applications/nibspark.desktop" ] || fail "the AppImage has no menu entry"

mkdir -p "$dir" "$(dirname "$entry")" "$(dirname "$icon")"
app="$dir/$name"
# Replace the AppImage atomically, so a running copy isn't affected.
mv -f "$download" "$app.new"
mv -f "$app.new" "$app"
cp "$share/icons/hicolor/512x512/apps/nibspark.png" "$icon"
# Point Exec and TryExec at the installed AppImage (quoted, in case the
# path has spaces), keeping the files it's handed, as "Open with" does.
sed -e "s|^Exec=.*|Exec=\"$app\" %F|" -e "/^TryExec=/d" \
  -e "/^\[Desktop Entry\]/a TryExec=$app" \
  "$share/applications/nibspark.desktop" >"$entry"
refresh

# Add ~/.local/bin/nibspark, unless something else already has that name.
linked=""
if [ ! -e "$link" ] && [ ! -L "$link" ] || ours "$link"; then
  mkdir -p "$(dirname "$link")"
  ln -sf "$app" "$link"
  linked=1
fi

say ""
say "nibspark $VERSION is installed. Open it from your apps menu."
if [ -n "$linked" ]; then
  case ":$PATH:" in
    *":$HOME/.local/bin:"*) say "Or run nibspark in a terminal." ;;
    *) say "Or run $link in a terminal (~/.local/bin isn't in your PATH)." ;;
  esac
fi
say "nibspark supports auto-updating, so there's no need to run this again."
say "To uninstall: curl -fsSL https://nibspark.app/install.sh | sh -s -- --uninstall"
