#!/usr/bin/env bash
# oslo-wall installer for sway (wlroots), KDE Plasma 6 and GNOME 45+ (Debian/Ubuntu, Arch, Fedora).
#
#   curl -fsSL https://oslowall.kingtalgo.com/downloads/oslo-wall/install.sh | bash
#   wget -qO- https://oslowall.kingtalgo.com/downloads/oslo-wall/install.sh | bash   (no curl)
#   ./install.sh [--widget URL [--key KEY] [--title T]] [--quality lite|ultra] [--no-deps] [--no-start]
#                [--desktop gnome|kde|sway] [--yes]
#   ./install.sh --uninstall [--yes]          (same as: oslowall uninstall)
#   ./install.sh --addon-deps NAME [--yes]    the packages of one addon (used by `oslowall addon enable`)
#
# Desktop: KDE Plasma gets a Plasma wallpaper plugin (org.oslowall.wallpaper); GNOME (and Ubuntu)
# gets a GNOME Shell extension (oslowall@kingtalgo.com) that keeps the scene behind the desktop;
# sway and other wlroots compositors get the layer-shell host. Only the packages for that desktop are installed,
# and only after you say yes (--yes answers yes; without a terminal and without --yes nothing is
# installed). Everything the installer creates is recorded, and the uninstaller removes it again.
#
# Run from a release or a git checkout, it installs that copy. Piped into bash (no files next to
# it), it downloads the newest release of its channel, checks the sha256 and runs that release's
# installer. It installs the dependencies, copies the app to ~/.local/share/oslo-wall, puts
# `oslowall` and `osw` (the control panel) in ~/.local/bin and on your PATH, and adds an autostart
# line plus a floating-window rule for the panel to your sway config. It never makes sway start
# at boot: start sway yourself from a TTY with `sway`.
set -euo pipefail

# ---- channel: tools/release.sh fills these in for the published copies of this file ----------
OW_LATEST_URL="${OW_LATEST_URL:-https://oslowall.kingtalgo.com/downloads/oslo-wall/latest.json}"
OW_CHANNEL="${OW_CHANNEL:-public}"
OW_WIDGET_URL="${OW_WIDGET_URL:-}"
OW_WIDGET_KEY="${OW_WIDGET_KEY:-}"
OW_WIDGET_TITLE="${OW_WIDGET_TITLE:-Claude}"
# ------------------------------------------------------------------------------------------------
OW_PUBLIC_LATEST="https://oslowall.kingtalgo.com/downloads/oslo-wall/latest.json"

DEST="$HOME/.local/share/oslo-wall"
BIN="$HOME/.local/bin"
CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/oslo-wall"
SWAY_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/sway/config"
MARK_BEGIN="# >>> oslo-wall >>>"
MARK_END="# <<< oslo-wall <<<"
PATH_BEGIN="# >>> oslo-wall path >>>"
PATH_END="# <<< oslo-wall path <<<"

say() { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m!!\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31mxx\033[0m %s\n' "$*" >&2; exit 1; }
redact() { sed -E 's#/p/([^/]{4})[^/]+/#/p/\1…/#' <<<"$1"; }

# Everything runs from main, so a download cut off halfway through `curl | bash` runs nothing.
main() {
  local WIDGET="" KEY="" TITLE="" QUALITY="" DEPS=1 START=1 MODE=install ADDON=""
  local ARGS=("$@")
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --widget) WIDGET="${2:?--widget needs a URL}"; shift 2 ;;
      --key) KEY="${2:?--key needs a value}"; shift 2 ;;
      --title) TITLE="${2:?--title needs a value}"; shift 2 ;;
      --quality) QUALITY="${2:?--quality needs lite or ultra}"; shift 2
                 [[ "$QUALITY" =~ ^(lite|ultra)$ ]] || die "--quality must be lite or ultra" ;;
      --channel) OW_LATEST_URL="${2:?--channel needs a latest.json URL}"; shift 2 ;;
      --no-deps) DEPS=0; shift ;;
      --no-start) START=0; shift ;;
      --yes|-y) ASSUME_YES=1; shift ;;
      --desktop) DESKTOP="${2:?--desktop needs gnome, kde or sway}"; shift 2
                 [[ "$DESKTOP" =~ ^(gnome|kde|sway)$ ]] || die "--desktop must be gnome, kde or sway" ;;
      --update) MODE=update; DEPS=0; shift ;;          # used by `oslowall update`
      --uninstall) MODE=uninstall; shift ;;
      --addon-deps) MODE=addon-deps; ADDON="${2:?--addon-deps needs an addon name}"; shift 2 ;;   # used by `oslowall addon enable`
      -h|--help) sed -n '2,26p' "${BASH_SOURCE[0]:-/dev/null}" 2>/dev/null || true; exit 0 ;;
      *) die "unknown option $1 (see --help)" ;;
    esac
  done
  # Baked-in widget settings (the personal installer) unless given on the command line.
  if [[ -z "$WIDGET" && -n "$OW_WIDGET_URL" ]]; then WIDGET="$OW_WIDGET_URL"; KEY="${KEY:-$OW_WIDGET_KEY}"; fi
  [[ -n "$TITLE" ]] || TITLE="$OW_WIDGET_TITLE"

  if [[ "$MODE" == uninstall ]]; then uninstall; return; fi
  if [[ "$MODE" == addon-deps ]]; then addon_deps "$ADDON"; return; fi

  local SRC=""
  if [[ -f "${BASH_SOURCE[0]:-}" && -f "$(dirname "${BASH_SOURCE[0]}")/web/index.html" ]]; then
    SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  fi
  if [[ -z "$SRC" ]]; then
    bootstrap "${ARGS[@]}"
    return
  fi

  local VERSION; VERSION="$(cat "$SRC/VERSION" 2>/dev/null || echo dev)"
  [[ -n "$DESKTOP" ]] || DESKTOP="$(detect_desktop)"
  if [[ "$MODE" == update ]]; then say "Updating oslo-wall to $VERSION"; else say "Installing oslo-wall $VERSION"; fi
  case "$DESKTOP" in
    kde) say "Desktop: KDE Plasma (wallpaper plugin)" ;;
    gnome) say "Desktop: GNOME (Shell extension)" ;;
    *) say "Desktop: sway / wlroots (layer-shell)" ;;
  esac
  track "$CONF_DIR"; mkdir -p "$CONF_DIR"
  if (( DEPS )); then install_deps; else check_deps || true; fi
  copy_files "$SRC"
  write_config "$WIDGET" "$KEY" "$TITLE" "$QUALITY" "$VERSION"
  if [[ "$DESKTOP" == kde ]]; then
    install_plasma "$VERSION"
  elif [[ "$DESKTOP" == gnome ]]; then
    install_gnome "$VERSION"
  else
    hook_sway
  fi
  install_launchers
  add_path
  if [[ "$DESKTOP" == gnome ]]; then
    if [[ "$MODE" == update ]]; then
      # the extension starts the new renderer by itself; new extension code loads at the next login
      if [[ "$("$BIN/oslowall" status 2>/dev/null || true)" == running* ]]; then "$BIN/oslowall" restart >/dev/null 2>&1 || true; fi
      echo "oslo-wall $VERSION installed"; return
    fi
    if (( START )) && [[ "$(json_get "$CONF_DIR/config.json" enabled)" != False ]]; then
      say "Turning on the Oslo Wall GNOME Shell extension"
      "$BIN/oslowall" start >/dev/null || warn "could not turn it on now: run oslowall start"
      gnome-extensions info "$GNOME_UUID" >/dev/null 2>&1 || GNOME_RELOGIN=1
    fi
    done_text
    if (( ${GNOME_RELOGIN:-0} )); then
      echo
      say "GNOME loads a new extension at login: log out and back in once, and the wallpaper is there (and from then on by itself)."
      if confirm "Log out now (save your work first)?"; then gnome-session-quit --logout --no-prompt || true; fi
    fi
    return
  fi
  if [[ "$DESKTOP" == kde ]]; then
    if [[ "$MODE" == update ]]; then
      if [[ "$("$BIN/oslowall" status 2>/dev/null || true)" == running* ]]; then "$BIN/oslowall" restart >/dev/null 2>&1 || true; fi
      echo "oslo-wall $VERSION installed"; return
    fi
    if (( START )) && [[ "$(json_get "$CONF_DIR/config.json" enabled)" != False ]]; then
      say "Setting Oslo Wall as the Plasma wallpaper"
      "$BIN/oslowall" start || warn "could not set it now: right-click the desktop > Configure Desktop and Wallpaper > Oslo Wall"
    fi
    done_text; return
  fi
  if [[ "$MODE" == update ]]; then
    # Restart only a wallpaper that is running now.
    # (no `status | grep -q` here: with pipefail, grep quitting early fails the pipeline on SIGPIPE)
    local st; st="$("$BIN/oslowall" status 2>/dev/null || true)"
    if [[ "$st" == running* ]]; then "$BIN/oslowall" restart >/dev/null 2>&1 || warn "restart failed"; fi
    echo "oslo-wall $VERSION installed"
    return
  fi
  if (( START )) && sway_running; then
    say "Starting the wallpaper"
    "$BIN/oslowall" restart >/dev/null 2>&1 || warn "could not start it now; it starts with sway (log: ~/.cache/oslo-wall/host.log)"
  fi
  done_text
}

done_text() {
  cat <<EOF

Done: oslo-wall $VERSION. The wallpaper runs by itself at login (turn that off in the editor's Settings).
  Oslo Wall (app menu) or oslowall   the editor
  osw                  quick control panel: time, weather, wave text, widget, updates (Esc closes it)
  oslowall help        every command
  oslowall update      upgrade to the newest version
  oslowall uninstall   remove everything oslo-wall added
EOF
  if [[ ":$PATH:" != *":$BIN:"* ]]; then echo "Open a new terminal (or run: export PATH=\"$BIN:\$PATH\") to use the commands."; fi
}

# ---- piped install: fetch the newest release of this channel, verify it, run its installer ----
bootstrap() {
  local latest="${OW_LATEST_URL:-$OW_PUBLIC_LATEST}"
  command -v python3 >/dev/null || die "python3 is needed"
  fetch() {  # fetch URL FILE: curl, or wget (a fresh Ubuntu has no curl)
    if command -v curl >/dev/null; then curl -fsSL --retry 2 "$1" -o "$2"; else wget -q --tries=3 -O "$2" "$1"; fi
  }
  command -v curl >/dev/null || command -v wget >/dev/null || die "curl or wget is needed"
  local tmp; tmp="$(mktemp -d)"
  # shellcheck disable=SC2064
  trap "rm -rf '$tmp'" EXIT
  say "Fetching the newest oslo-wall"
  fetch "$latest" "$tmp/latest.json" || die "could not download $(redact "$latest")"
  local meta ver url sha size
  meta="$(python3 - "$tmp/latest.json" "$latest" <<'PY'
import json, re, sys, urllib.parse
d = json.load(open(sys.argv[1]))
assert re.fullmatch(r"\d+\.\d+\.\d+", d["version"]) and re.fullmatch(r"[0-9a-f]{64}", d["sha256"])
print(d["version"], urllib.parse.urljoin(sys.argv[2], d["url"]), d["sha256"], int(d["size"]))
PY
  )" || die "latest.json is not valid"
  read -r ver url sha size <<<"$meta"
  fetch "$url" "$tmp/release.tar.gz" || die "could not download the release"
  [[ "$(stat -c %s "$tmp/release.tar.gz")" == "$size" ]] || die "the download is incomplete"
  echo "$sha  $tmp/release.tar.gz" | sha256sum -c --quiet - || die "checksum mismatch: not installing"
  tar -xzf "$tmp/release.tar.gz" -C "$tmp" --no-same-owner
  [[ -f "$tmp/oslo-wall-$ver/install.sh" ]] || die "the release is incomplete"
  say "Verified oslo-wall $ver (sha256 ok)"
  # The release's installer gets this channel (and the baked-in widget settings) through the
  # environment, never on the command line, where `ps` would show the key.
  OW_LATEST_URL="$latest" OW_CHANNEL="${OW_CHANNEL:-public}" OW_WIDGET_URL="$OW_WIDGET_URL" \
    OW_WIDGET_KEY="$OW_WIDGET_KEY" OW_WIDGET_TITLE="$OW_WIDGET_TITLE" bash "$tmp/oslo-wall-$ver/install.sh" "$@"
}

# ---- desktop detection ------------------------------------------------------------------------
detect_desktop() {
  local d="${XDG_CURRENT_DESKTOP:-}${DESKTOP_SESSION:-}"
  if [[ "${d,,}" == *kde* || "${d,,}" == *plasma* ]] || pgrep -u "$(id -u)" -x plasmashell >/dev/null 2>&1; then echo kde; return; fi
  if [[ "${d,,}" == *gnome* || "${d,,}" == *ubuntu* ]] || pgrep -u "$(id -u)" -x gnome-shell >/dev/null 2>&1; then echo gnome; return; fi
  echo sway
}

# ---- record of what this installer created (the uninstaller removes exactly that) ---------------
CREATED="$CONF_DIR/created.list"      # paths that did not exist before the install
PKGS_FILE="$CONF_DIR/packages.list"   # packages this installer installed (removed on uninstall, after asking)
track() {  # track PATH: record PATH and its missing parent directories under $HOME before creating them
  local p="$1" missing=()
  while [[ "$p" == "$HOME"/* && ! -e "$p" ]]; do missing+=("$p"); p="$(dirname "$p")"; done
  (( ${#missing[@]} )) || return 0
  mkdir -p "$CONF_DIR"
  printf '%s\n' "${missing[@]}" >> "$CREATED"
}
json_get() { python3 -c 'import json,sys; v=json.load(open(sys.argv[1])).get(sys.argv[2]); print("" if v is None else v)' "$1" "$2" 2>/dev/null || true; }

ASSUME_YES="${ASSUME_YES:-0}"
DESKTOP="${DESKTOP:-}"
confirm() {  # confirm "question": yes with --yes; otherwise ask on the terminal (no terminal = no)
  (( ASSUME_YES )) && return 0
  local a=""
  if [[ -r /dev/tty ]] && { : </dev/tty; } 2>/dev/null; then
    printf '\033[1;33m??\033[0m %s [y/N] ' "$1" >/dev/tty
    read -r a </dev/tty || a=""
  else
    warn "no terminal to ask: $1 (rerun with --yes to accept)"
  fi
  [[ "$a" =~ ^[Yy] ]]
}

# ---- dependencies (only the ones for this desktop) ----------------------------------------------
pkg_mgr() { if command -v apt-get >/dev/null; then echo apt; elif command -v pacman >/dev/null; then echo pacman; elif command -v dnf >/dev/null; then echo dnf; fi; }
want_packages() {
  local pm; pm="$(pkg_mgr)"
  case "$pm:$DESKTOP" in
    apt:sway)    echo sway swaybg grim python3-gi gir1.2-webkit2-4.1 gir1.2-gtklayershell-0.1 fonts-inter ;;
    apt:kde)     echo python3-gi gir1.2-webkit2-4.1 qml6-module-qtwebengine qml6-module-qtcore fonts-inter ;;
    pacman:sway) echo sway swaybg grim python-gobject webkit2gtk-4.1 gtk-layer-shell inter-font ;;
    pacman:kde)  echo python-gobject webkit2gtk-4.1 qt6-webengine inter-font ;;
    dnf:sway)    echo sway swaybg grim python3-gobject webkit2gtk4.1 gtk-layer-shell rsms-inter-fonts ;;
    dnf:kde)     echo python3-gobject webkit2gtk4.1 qt6-qtwebengine rsms-inter-fonts ;;
    apt:gnome)   echo python3-gi python3-gi-cairo gir1.2-webkit2-4.1 fonts-inter ;;
    pacman:gnome) echo python-gobject python-cairo webkit2gtk-4.1 inter-font ;;
    dnf:gnome)   echo python3-gobject python3-cairo webkit2gtk4.1 rsms-inter-fonts ;;
  esac
}
pkg_installed() {
  case "$(pkg_mgr)" in
    apt) dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q "install ok installed" ;;
    pacman) pacman -Qq "$1" >/dev/null 2>&1 ;;
    dnf) rpm -q "$1" >/dev/null 2>&1 ;;
    *) return 0 ;;
  esac
}

check_deps() {
  local missing=() c
  if [[ "$DESKTOP" == sway ]]; then for c in sway grim; do command -v "$c" >/dev/null || missing+=("$c"); done; fi
  command -v python3 >/dev/null || missing+=(python3)
  if [[ "$DESKTOP" == gnome ]]; then
    command -v gnome-extensions >/dev/null || missing+=("gnome-extensions (GNOME Shell 45+)")
    local p; for p in $(want_packages); do pkg_installed "$p" || missing+=("$p"); done
  elif [[ "$DESKTOP" == kde ]]; then
    command -v kpackagetool6 >/dev/null || missing+=("kpackagetool6 (Plasma 6)")
    local p; for p in $(want_packages); do pkg_installed "$p" || missing+=("$p"); done
  else
    python3 - <<'PY' 2>/dev/null || missing+=("python3-gi/webkit2gtk-4.1/gtk-layer-shell")
import gi
gi.require_version("Gtk", "3.0"); gi.require_version("WebKit2", "4.1"); gi.require_version("GtkLayerShell", "0.1")
from gi.repository import Gtk, WebKit2, GtkLayerShell  # noqa: F401
PY
  fi
  if (( ${#missing[@]} )); then warn "missing: ${missing[*]} (run install.sh without --no-deps)"; return 1; fi
  return 0
}

dpkg_installed() { dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null | awk '$1 == "ii" {print $2}' | LC_ALL=C sort; }

install_deps() {
  local pm need=() p
  pm="$(pkg_mgr)"
  [[ -n "$pm" ]] || { check_deps || warn "unknown distro: install the packages listed above yourself"; return 0; }
  for p in $(want_packages); do pkg_installed "$p" || need+=("$p"); done
  if (( ${#need[@]} == 0 )); then say "Dependencies are already installed"; return; fi
  if ! confirm "Install these packages with sudo ($pm): ${need[*]}?"; then
    warn "not installing packages; oslo-wall may not run until you install: ${need[*]}"
    return 0
  fi
  install_pkgs "$pm" "${need[@]}"
}

install_pkgs() {  # install_pkgs PM PKG...: install and record what is new (the uninstaller offers to remove it)
  local pm="$1" p; shift
  local need=("$@")
  say "Installing: ${need[*]}"
  local before=""
  if [[ "$pm" == apt ]]; then before="$(dpkg_installed)"; fi
  case "$pm" in
    apt) sudo apt-get update -q || warn "apt-get update failed; trying the install anyway"
         sudo apt-get install -y "${need[@]}"
         # apt pulls in dependencies too: record every package that is new, so the uninstaller can
         # remove exactly those (and never runs autoremove, which would take unrelated packages)
         { LC_ALL=C comm -13 <(echo "$before") <(dpkg_installed) | sed '/^$/d' >> "$PKGS_FILE"; } || true
         return 0 ;;
    pacman) sudo pacman -S --needed --noconfirm "${need[@]}" ;;
    dnf) sudo dnf install -y "${need[@]}" ;;
  esac
  # remember what we installed ourselves, so `oslowall uninstall` can offer to remove it
  for p in "${need[@]}"; do pkg_installed "$p" && echo "$p" >> "$PKGS_FILE"; done
  return 0
}

# ---- addons: the packages one addon needs on this desktop (its manifest.json "deps") ---------------
addon_deps() {
  local name="$1" pm need=() p desk="${OW_ADDON_DESKTOP:-}"
  local manifest="$DEST/addons/$name/manifest.json"
  [[ -f "$manifest" ]] || manifest="$(dirname "${BASH_SOURCE[0]}")/addons/$name/manifest.json"
  [[ -f "$manifest" ]] || die "unknown addon $name"
  [[ -n "$desk" ]] || desk="$(json_get "$CONF_DIR/install.json" desktop)"
  [[ -n "$desk" ]] || desk="$(detect_desktop)"
  pm="$(pkg_mgr)"
  [[ -n "$pm" ]] || { warn "unknown package manager: install the packages for $name yourself (see $manifest)"; return 0; }
  for p in $(python3 -c 'import json,sys; print(" ".join(json.load(open(sys.argv[1])).get("deps", {}).get(sys.argv[2], {}).get(sys.argv[3], [])))' "$manifest" "$pm" "$desk"); do
    pkg_installed "$p" || need+=("$p")
  done
  if (( ${#need[@]} == 0 )); then say "$name: dependencies are already installed"; return 0; fi
  if ! confirm "The $name addon needs these packages. Install them with sudo ($pm): ${need[*]}?"; then
    warn "not installing packages for $name: ${need[*]}"
    return 0
  fi
  track "$CONF_DIR"; mkdir -p "$CONF_DIR"
  install_pkgs "$pm" "${need[@]}"
}

# ---- files: copy next to the old version, then swap (the old one stays until the new one is in) --
copy_files() {
  local src="$1" item
  say "Copying files to $DEST"
  track "$DEST"; track "$BIN/oslowall"; track "$BIN/osw"
  mkdir -p "$(dirname "$DEST")" "$BIN" "$CONF_DIR"
  rm -rf "$DEST.new" "$DEST.old"
  mkdir -p "$DEST.new"
  for item in bin host web gui lib plasma gnome addons install.sh VERSION README.md; do
    if [[ -e "$src/$item" ]]; then cp -r "$src/$item" "$DEST.new/"; fi
  done
  find "$DEST.new" -name '__pycache__' -prune -exec rm -rf {} +
  chmod +x "$DEST.new"/bin/* "$DEST.new/host/oslowall-host.py" "$DEST.new/install.sh"
  if [[ -f "$DEST.new/gui/oslowall-gui.py" ]]; then chmod +x "$DEST.new/gui/oslowall-gui.py"; fi
  if [[ -d "$DEST" ]]; then
    # keep user state (account.json sign-in, locks, caches): everything that isn't an app file
    local keep
    for keep in "$DEST"/* "$DEST"/.[!.]*; do
      [[ -e "$keep" ]] || continue
      case "$(basename "$keep")" in bin|host|web|gui|lib|plasma|gnome|addons|install.sh|VERSION|README.md) ;; *) cp -a "$keep" "$DEST.new/" ;; esac
    done
    mv "$DEST" "$DEST.old"
    if ! mv "$DEST.new" "$DEST"; then mv "$DEST.old" "$DEST"; die "could not put the new version in place"; fi
    rm -rf "$DEST.old"
  else
    mv "$DEST.new" "$DEST"
  fi
  ln -sfn "$DEST/bin/oslowall" "$BIN/oslowall"
  ln -sfn "$DEST/bin/osw" "$BIN/osw"
}

# ---- config -----------------------------------------------------------------------------------
write_config() {
  local widget="$1" key="$2" title="$3" quality="$4" version="$5"
  if [[ ! -f "$CONF_DIR/state.json" ]]; then echo '{}' > "$CONF_DIR/state.json"; fi
  OW_W="$widget" OW_K="$key" OW_T="$title" OW_Q="$quality" OW_V="$version" \
  OW_D="$DESKTOP" OW_L="$OW_LATEST_URL" OW_C="$OW_CHANNEL" OW_PUB="$OW_PUBLIC_LATEST" python3 - "$CONF_DIR" <<'PY'
import json, os, sys, time
conf, e = sys.argv[1], os.environ
def load(name):
    try:
        d = json.load(open(os.path.join(conf, name)))
        return d if isinstance(d, dict) else {}
    except (OSError, ValueError):
        return {}
def save(name, d, mode):
    p = os.path.join(conf, name)
    with open(p + ".tmp", "w") as f:
        json.dump(d, f, indent=2); f.write("\n")
    os.chmod(p + ".tmp", mode)
    os.replace(p + ".tmp", p)
cfg = load("config.json")
new = not cfg
cfg.setdefault("enabled", True)
if e["OW_Q"] or new:
    cfg["quality"] = e["OW_Q"] or "lite"
if e["OW_W"]:
    w = {"url": e["OW_W"], "title": e["OW_T"] or "Claude"}
    if e["OW_K"]:
        w["key"] = e["OW_K"]
    cfg["widget"] = w
# The config may hold the widget key: keep it private.
save("config.json", cfg, 0o600)
inst = load("install.json")
if e["OW_L"]:
    inst["latest"] = e["OW_L"]
    inst["channel"] = e["OW_C"] or ("public" if e["OW_L"] == e["OW_PUB"] else inst.get("channel") or "custom")
inst["version"] = e["OW_V"]
inst["desktop"] = e["OW_D"] or "sway"
inst["installed_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
save("install.json", inst, 0o600)  # a personal channel URL carries the download token
PY
  if [[ -n "$widget" ]]; then say "Usage widget: $(redact "$widget")${key:+ (with its key)}"; fi
}

# ---- sway: autostart + a floating, centred panel (it sizes itself to 75% of the output; a sway
# "resize set 75 ppt" would use the area minus the bar and fight the fixed size, so none here) ----
sway_block() {
  cat <<EOF
$MARK_BEGIN
# Oslo live wallpaper (oslowall help). Managed by the oslo-wall installer.
exec_always $BIN/oslowall autostart
for_window [app_id="oslowall-gui"] floating enable, border none, move position center
$MARK_END
EOF
}

strip_sway_block() {  # our block, and the v1 single autostart line with its comment
  sed -i -e "\|^$MARK_BEGIN\$|,\|^$MARK_END\$|d" -e '\|oslowall autostart|d' \
    -e '\|^# Oslo live wallpaper (toggle with|d' "$SWAY_CONF"
}

hook_sway() {
  say "Hooking into the sway config"
  if [[ ! -f "$SWAY_CONF" ]]; then
    track "$SWAY_CONF"
    mkdir -p "$(dirname "$SWAY_CONF")"
    cp /etc/sway/config "$SWAY_CONF" 2>/dev/null || touch "$SWAY_CONF"
  fi
  local before; before="$(cat "$SWAY_CONF")"
  strip_sway_block
  sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$SWAY_CONF"   # drop trailing blank lines
  { echo; sway_block; } >> "$SWAY_CONF"
  if [[ "$before" != "$(cat "$SWAY_CONF")" ]] && sway_running; then swaymsg reload >/dev/null 2>&1 || true; fi
}

sway_running() {
  [[ -n "${SWAYSOCK:-}" ]] || ls "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/sway-ipc.* >/dev/null 2>&1
}

# ---- the editor in the app launcher + the wallpaper as its own background service ----------------
APPS_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
AUTOSTART_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/autostart"
has_systemd_user() { command -v systemctl >/dev/null && systemctl --user show-environment >/dev/null 2>&1; }

install_launchers() {
  say "Adding the Oslo Wall editor to the app launcher"
  track "$APPS_DIR/oslo-wall.desktop"
  mkdir -p "$APPS_DIR"
  cat > "$APPS_DIR/oslo-wall.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Oslo Wall
Comment=Edit the Oslo live wallpaper: time, weather, wave text, widgets, autostart
Exec=$BIN/oslowall
Icon=preferences-desktop-wallpaper
Terminal=false
Categories=Settings;DesktopSettings;
StartupWMClass=oslowall-gui
EOF
  local enabled; enabled="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("enabled", True) is not False)' "$CONF_DIR/config.json" 2>/dev/null || echo True)"
  if [[ "$DESKTOP" == kde || "$DESKTOP" == gnome ]]; then
    # Plasma runs the wallpaper plugin itself, GNOME Shell our extension: no service, no autostart entry
    rm -f "$UNIT_DIR/oslo-wall.service" "$AUTOSTART_DIR/oslo-wall.desktop"
    return 0
  fi
  if has_systemd_user; then
    say "Setting up the background service (systemd --user oslo-wall.service)"
    track "$UNIT_DIR/oslo-wall.service"
    mkdir -p "$UNIT_DIR"
    cat > "$UNIT_DIR/oslo-wall.service" <<EOF
[Unit]
Description=Oslo live wallpaper (oslo-wall)
PartOf=graphical-session.target
After=graphical-session.target

[Service]
ExecStart=$BIN/oslowall run
Restart=on-failure
RestartSec=3

[Install]
WantedBy=graphical-session.target
EOF
    systemctl --user daemon-reload || true
    rm -f "$AUTOSTART_DIR/oslo-wall.desktop"
  else
    track "$AUTOSTART_DIR/oslo-wall.desktop"
    mkdir -p "$AUTOSTART_DIR"
    cat > "$AUTOSTART_DIR/oslo-wall.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Oslo Wall (background)
Exec=$BIN/oslowall autostart
NoDisplay=true
X-GNOME-Autostart-enabled=true
EOF
  fi
  # Respects the login setting (on for a fresh install).
  if [[ "$enabled" == True ]]; then "$BIN/oslowall" login on >/dev/null; else "$BIN/oslowall" login off >/dev/null; fi
}

remove_launchers() {
  if [[ -f "$UNIT_DIR/oslo-wall.service" ]]; then
    systemctl --user disable --now oslo-wall.service >/dev/null 2>&1 || true
    rm -f "$UNIT_DIR/oslo-wall.service"
    systemctl --user daemon-reload >/dev/null 2>&1 || true
  fi
  rm -f "$APPS_DIR/oslo-wall.desktop" "$AUTOSTART_DIR/oslo-wall.desktop"
}

# ---- PATH: ~/.local/bin via ~/.profile (login shells and sway) and the interactive rc files -------
add_path() {
  local f line="case \":\$PATH:\" in *\":\$HOME/.local/bin:\"*) ;; *) export PATH=\"\$HOME/.local/bin:\$PATH\" ;; esac"
  for f in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.zshrc"; do
    [[ "$f" == "$HOME/.profile" || -f "$f" ]] || continue
    grep -qF "$PATH_BEGIN" "$f" 2>/dev/null && continue
    grep -q '\.local/bin' "$f" 2>/dev/null && continue    # the distro's ~/.profile already does it
    track "$f"
    printf '\n%s\n%s\n%s\n' "$PATH_BEGIN" "$line" "$PATH_END" >> "$f"
  done
  if command -v fish >/dev/null && [[ -d "$HOME/.config/fish" ]]; then
    track "$HOME/.config/fish/conf.d/oslo-wall.fish"
    mkdir -p "$HOME/.config/fish/conf.d"
    echo 'fish_add_path -g $HOME/.local/bin' > "$HOME/.config/fish/conf.d/oslo-wall.fish"
  fi
  return 0
}

remove_path() {
  local f
  for f in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.zshrc"; do
    [[ -f "$f" ]] && grep -qF "$PATH_BEGIN" "$f" || continue
    python3 - "$f" "$PATH_BEGIN" "$PATH_END" <<'PY'
import re, sys
f, b, e = sys.argv[1:4]
s = open(f).read()
s = re.sub(r"\n?" + re.escape(b) + r"\n.*?" + re.escape(e) + r"\n?", "", s, flags=re.S)
open(f, "w").write(s)
PY
    say "removed the PATH lines from $f"
  done
  rm -f "$HOME/.config/fish/conf.d/oslo-wall.fish"
}

# ---- KDE Plasma 6: a wallpaper plugin (KPackage Plasma/Wallpaper) that shows the web scene -------
PLASMA_ID="org.oslowall.wallpaper"
install_plasma() {
  local version="$1" pkg="$DEST/plasma/$PLASMA_ID"
  track "$HOME/.pki"   # QtWebEngine creates ~/.pki/nssdb on first run; it goes again on uninstall if it is ours
  command -v kpackagetool6 >/dev/null || { warn "kpackagetool6 not found: is this Plasma 6?"; return 0; }
  sed -i "s/@VERSION@/$version/" "$pkg/metadata.json"
  chmod +x "$DEST/plasma/poll.sh"
  local target="${XDG_DATA_HOME:-$HOME/.local/share}/plasma/wallpapers/$PLASMA_ID"
  track "$target"
  if [[ -d "$target" ]]; then
    say "Updating the Plasma wallpaper plugin"
    kpackagetool6 -t Plasma/Wallpaper -u "$pkg" >/dev/null
  else
    say "Installing the Plasma wallpaper plugin ($PLASMA_ID)"
    kpackagetool6 -t Plasma/Wallpaper -i "$pkg" >/dev/null
  fi
}

# ---- GNOME 45+: a Shell extension that runs the renderer and keeps it behind the desktop ----------
GNOME_UUID="oslowall@kingtalgo.com"
GNOME_EXT_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/gnome-shell/extensions/$GNOME_UUID"
GNOME_PREV="$CONF_DIR/gnome-previous.json"
install_gnome() {
  local version="$1"
  command -v gnome-extensions >/dev/null || warn "gnome-extensions not found: is this GNOME Shell 45 or newer?"
  if [[ ! -f "$GNOME_PREV" ]] && command -v dconf >/dev/null; then
    # what the extension lists looked like before us, so the uninstaller can put them back exactly
    (umask 077; python3 -c 'import json,sys; print(json.dumps({"enabled": sys.argv[1], "disabled": sys.argv[2]}))'       "$(dconf read /org/gnome/shell/enabled-extensions)" "$(dconf read /org/gnome/shell/disabled-extensions)" > "$GNOME_PREV")
  fi
  if [[ "$(gsettings get org.gnome.shell disable-user-extensions 2>/dev/null)" == true ]]; then
    if confirm "User extensions are switched off in GNOME. Switch them on (needed for the wallpaper)?"; then
      gsettings set org.gnome.shell disable-user-extensions false
    else
      warn "user extensions stay off: the wallpaper cannot run until you turn them on (Extensions app)"
    fi
  fi
  track "$GNOME_EXT_DIR"
  say "$( [[ -d "$GNOME_EXT_DIR" ]] && echo Updating || echo Installing ) the GNOME Shell extension ($GNOME_UUID)"
  rm -rf "$GNOME_EXT_DIR"
  mkdir -p "$GNOME_EXT_DIR"
  cp -r "$DEST/gnome/$GNOME_UUID/." "$GNOME_EXT_DIR/"
  sed -i "s/@VERSION@/$version/" "$GNOME_EXT_DIR/metadata.json"
}

uninstall_gnome() {
  [[ -d "$GNOME_EXT_DIR" || -f "$GNOME_PREV" ]] || return 0
  if command -v gnome-extensions >/dev/null; then gnome-extensions disable "$GNOME_UUID" >/dev/null 2>&1 || true; fi
  pkill -u "$(id -u)" -f "oslowall-host.py --gnome" 2>/dev/null || true
  if command -v dconf >/dev/null; then
    python3 - "$GNOME_UUID" "$GNOME_PREV" <<'PY' || true
import ast, json, subprocess, sys
uuid, prev_file = sys.argv[1], sys.argv[2]
try:
    prev = json.load(open(prev_file))
except (OSError, ValueError):
    prev = {}
for key, name in (("enabled-extensions", "enabled"), ("disabled-extensions", "disabled")):
    path = "/org/gnome/shell/" + key
    raw = subprocess.run(["dconf", "read", path], capture_output=True, text=True).stdout.strip()
    if not raw:
        continue
    cur = ast.literal_eval(raw.replace("@as ", ""))
    new = [u for u in cur if u != uuid]
    if not new and not prev.get(name):      # the key was not set before oslo-wall: unset it again
        subprocess.run(["dconf", "reset", path])
    elif new != cur:
        subprocess.run(["dconf", "write", path, str(new)])
PY
  fi
  rm -f "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/oslo-wall-gnome.json"
  if [[ -d "$GNOME_EXT_DIR" ]]; then rm -rf "$GNOME_EXT_DIR"; removed+=("$GNOME_EXT_DIR (GNOME Shell extension)"); fi
}

uninstall() {
  [[ -d "$CONF_DIR" || -d "$DEST" ]] || { echo "oslo-wall is not installed"; return 0; }
  local removed=() f
  rm_say() { local p; for p in "$@"; do if [[ -e "$p" || -L "$p" ]]; then rm -rf "$p"; removed+=("$p"); fi; done; }
  # 1. stop it (Plasma: put the previous wallpaper back first)
  if [[ -x "$BIN/oslowall" ]]; then "$BIN/oslowall" stop >/dev/null 2>&1 || true; fi
  if [[ -f "$DEST/lib/owaddon.py" ]]; then python3 "$DEST/lib/owaddon.py" stop-all >/dev/null 2>&1 || true; fi
  pkill -u "$(id -u)" -f "$DEST/addons/" 2>/dev/null || true
  pkill -f "$DEST/gui/oslowall-gui.py" 2>/dev/null || true
  pkill -f "$DEST/host/oslowall-host.py" 2>/dev/null || true
  local plug="${XDG_DATA_HOME:-$HOME/.local/share}/plasma/wallpapers/$PLASMA_ID"
  if [[ -d "$plug" ]]; then
    kpackagetool6 -t Plasma/Wallpaper -r "$PLASMA_ID" >/dev/null 2>&1 || true
    rm -rf "$plug"; removed+=("$plug (Plasma wallpaper plugin)")
  fi
  uninstall_gnome
  # 2. launchers, service, autostart, sway hook, PATH lines
  [[ -f "$UNIT_DIR/oslo-wall.service" ]] && systemctl --user disable --now oslo-wall.service >/dev/null 2>&1 || true
  rm_say "$UNIT_DIR/oslo-wall.service" "$APPS_DIR/oslo-wall.desktop" "$AUTOSTART_DIR/oslo-wall.desktop" \
    "$AUTOSTART_DIR/oslo-wall-addons.desktop"
  systemctl --user daemon-reload >/dev/null 2>&1 || true
  if [[ -f "$SWAY_CONF" ]] && grep -qF "$MARK_BEGIN" "$SWAY_CONF"; then
    strip_sway_block
    sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$SWAY_CONF"
    removed+=("$SWAY_CONF (the oslo-wall block)")
    if sway_running; then swaymsg reload >/dev/null 2>&1 || true; fi
  fi
  remove_path
  # 3. app, commands, caches, WebKit data of the editor
  rm_say "$DEST" "$DEST.new" "$DEST.old" "$BIN/oslowall" "$BIN/osw" "$HOME/.config/fish/conf.d/oslo-wall.fish" \
    "${XDG_CACHE_HOME:-$HOME/.cache}/oslo-wall" "${XDG_CACHE_HOME:-$HOME/.cache}/oslowall-gui" \
    "${XDG_DATA_HOME:-$HOME/.local/share}/oslowall-gui" "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/oslo-wall.pid"
  rm -f "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/oslo-wall-addon-*.pid "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/oslowall-wrt-*.lock
  # 4. files and folders the installer created (a sway config it copied, an empty ~/.profile, empty dirs)
  local created=() pkgs=()
  [[ -f "$CREATED" ]] && mapfile -t created < <(sort -u "$CREATED" | awk '{print length, $0}' | sort -rn | cut -d' ' -f2-)
  [[ -f "$PKGS_FILE" ]] && mapfile -t pkgs < <(sort -u "$PKGS_FILE")
  rm_say "$CONF_DIR"   # settings, sign-in state, install record
  for f in "${created[@]}"; do
    [[ "$f" == "$HOME"/* ]] || continue
    if [[ "$f" == "$HOME/.pki" ]]; then rm_say "$f"   # the NSS store QtWebEngine made for the wallpaper (there was none before)
    elif [[ -d "$f" && ! -L "$f" ]]; then rmdir "$f" 2>/dev/null && removed+=("$f/") || true
    elif [[ "$f" == "$SWAY_CONF" && -f "$f" ]]; then rm_say "$f"
    elif [[ -f "$f" ]] && ! grep -q '[^[:space:]]' "$f"; then rm_say "$f"   # e.g. a ~/.profile that only had our lines
    fi
  done
  echo "Removed:"; printf '  %s\n' "${removed[@]}"
  # 5. packages it installed itself
  local still=() p
  for p in "${pkgs[@]}"; do pkg_installed "$p" && still+=("$p"); done
  if (( ${#still[@]} )); then
    if confirm "Remove the packages oslo-wall installed: ${still[*]}?"; then
      case "$(pkg_mgr)" in
        apt) sudo apt-get remove -y "${still[@]}" ;;   # no autoremove: it would also take unrelated packages (old kernels)
        pacman) sudo pacman -Rns --noconfirm "${still[@]}" ;;
        dnf) sudo dnf remove -y "${still[@]}" ;;
      esac && printf '  package %s\n' "${still[@]}"
    else
      echo "Kept the packages: ${still[*]}"
    fi
  fi
  echo "oslo-wall removed."
}

main "$@"
