#!/usr/bin/env bash
set -Eeuo pipefail

# Derived from ArchiveBox:
# https://github.com/pirate/ArchiveBox/blob/db1f6efc934bbcdf53377bf51a064c6fd0fc5b1d/bin/archivebox-export-browser-history#L23-L37
QUERY=$(cat <<EOF
SELECT "["
         ||
           group_concat(json_object('timestamp', dateAdded, 'description', title, 'href', url))
         ||
       "]"
FROM (
  SELECT b.dateAdded, b.title, p.url
  FROM moz_bookmarks AS b
  JOIN moz_places AS p
  ON b.fk = p.id
  WHERE b.fk IN (
    SELECT DISTINCT(fk) FROM moz_bookmarks
    WHERE parent IN (
      -- get all tags
      SELECT id FROM moz_bookmarks
      WHERE parent = 4
    )
  )
  ORDER BY
    b.dateAdded ASC,
    b.title ASC,
    p.url
)
EOF
)

# copy the database to avoid locking issues
TMPDB="$(mktemp)"
cp ~/.mozilla/firefox/*.default/places.sqlite "$TMPDB"

mkdir -p "$HOME/UTCLOUD/archive-box/"
cd "$HOME/UTCLOUD/archive-box/"

# I gave up on proper packaging for now, I'll stick with Docker
# while I regain energy and try again later
docker run -v "$PWD:/data" -ti archivebox/archivebox init
cat <<EOF > ArchiveBox.conf
[SERVER_CONFIG]
SECRET_KEY = c2.o66u!7!tdfohba7r7w!qhgb9.+1hmjtg_lfvebucus6pow3
SAVE_MEDIA=False
EOF
sqlite3 "$TMPDB" "${QUERY}" | docker run -v "$PWD:/data" -i archivebox/archivebox add

# Start server with:
# $ cd "$HOME/UTCLOUD/archive-box/"
# $ docker run -v $PWD:/data -it -p 8000:8000 archivebox/archivebox
