#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash -p dconf -p libsecret -p procps -p systemdMinimal

help() {
  echo "usage: sane-wipe <resource>"
  echo "resource:"
  echo "  browser: kill and remove cache for firefox, chromium, brave, etc"
  echo "  dino:    remove auth and data for Dino XMPP messenger"
  echo "  flare:   remove auth and data for flare-signal messenger"
  echo "  fractal: remove auth and data for fractal matrix messenger"
  echo "  rofi:    remove rofi .desktop entry cache and force it to recompute entries"
  exit 1
}


wipe_browser() {
  # remove chromium/epiphany/firefox/librewolf artifacts
  rm -rf \
    ~/.cache/BraveSoftware/* \
    ~/.cache/chromium/* \
    ~/.cache/epiphany/* \
    ~/.cache/librewolf/* \
    ~/.cache/mozilla/firefox/* \
    ~/.config/BraveSoftware/* \
    ~/.config/chromium/* \
    ~/.librewolf/default/* \
    ~/.local/share/epiphany/* \
    ~/.mozilla/firefox/default/* \
    || true  # in case no matches

  # browsers like to stick around in the background so they can load faster
  pkill brave || true
  pkill epiphany || true
  pkill firefox || true
  pkill librewolf || true
}

wipe_dino() {
  rm -rf ~/.local/share/dino/*
  echo "now re-launch Dino and join some notable channels like:"
  echo "- discuss@conference.soprani.ca"
}

wipe_flare() {
  secret-tool search --all --unlock 'xdg:schema' 'de.schmidhuberj.Flare'
  secret-tool clear 'xdg:schema' 'de.schmidhuberj.Flare'

  dconf reset -f /de/schmidhuberj/Flare/

  rm -rf ~/.local/share/flare/*

  echo "Flare is wiped: you may now repair it."
}

wipe_fractal() {
  systemctl stop fractal

  # first, ensure the relevant secrets are unlocked
  secret-tool search --all --unlock 'xdg:schema' 'org.gnome.Fractal'
  secret-tool search --all --unlock 'xdg:schema' 'org.gnome.Fractal.Hack'

  # then, delete them
  secret-tool clear 'xdg:schema' 'org.gnome.Fractal'
  secret-tool clear 'xdg:schema' 'org.gnome.Fractal.Hack'

  echo "Fractal is wiped: you may now restart it and login."
  echo "The initial sync may take up to an hour, after which you will be prompted to verify the session with another device."
  echo "If this does not work, try deleting ~/.local/share/fractal/* in its entirety."
}

wipe_rofi() {
  rm -f ~/.cache/rofi/rofi-drun-desktop.cache
}


case "$1" in
  (browser)
    wipe_browser
    ;;
  (dino)
    wipe_dino
    ;;
  (flare)
    wipe_flare
    ;;
  (fractal)
    wipe_fractal
    ;;
  (rofi)
    wipe_rofi
    ;;
  *)
    help
esac
