#!/usr/bin/env nix-shell
#!nix-shell --pure -i bash -p dejsonlz4 jq bash -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/fea633695211167753ee732c9087808d0c57461c.tar.gz

# Usage: ./export-firefox-bookmarks.sh [path/to/.mozilla/firefox/XXXXXXXX.profile]

set -euET -o pipefail

if test $# -ge 1; then
  profile="$1"
else
  # use printf to avoid echo's ambiguity; sort for determinism; use null separator (only byte illegal in UNIX paths, save trailing whitespace with a dummy x (not needed here as the string ends with "default", but a good habit nevertheless)
  profile="$(printf "%s"\\0 ~/.mozilla/firefox/*.default | sort -z | head -z -n 1 | tr -d \\0; printf "x")"
  profile="${profile%x}"
fi

if test -e "$profile"/sessionstore-backups/recovery.jsonlz4; then
  sessionstore="$profile"/sessionstore-backups/recovery.jsonlz4
elif test -e "$profile"/sessionstore.jsonlz4; then
  sessionstore="$profile"/sessionstore.jsonlz4
elif test -e "$profile"/sessionstore.js; then
  sessionstore="$profile"/sessionstore.js
else
  printf "Could not find session store at $profile/sessionstore-backups/recovery.jsonlz4 or $profile/sessionstore.jsonlz4 or $profile/sessionstore.js"
  exit 1
fi

# TODO: when the name is sessionstore.js, it might not need a decompression with dejsonlz4 ?
# Tabs from all windows are printed together, edit the jq expression to your needs. The input format is described at https://wiki.mozilla.org/Firefox/session_restore#For_developers
dejsonlz4 "$sessionstore" | jq '.windows[].tabs[].entries[-1].url'