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

QUERY=$(cat <<EOF
SELECT "["
         ||
           group_concat(json_object('title', title, 'url', url))
         ||
       "]"
FROM (
  SELECT b.title, p.url
  FROM moz_bookmarks AS b
  JOIN moz_places AS p
  ON b.fk = p.id
  WHERE b.fk NOT 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"

if [[ ! -d ./node_modules/ ]]; then
  npm ci
fi

mkdir -p ~/.elfeed/
sqlite3 "$TMPDB" "${QUERY}" | node elfeed.js > ~/.elfeed/ril.xml

timeout 120                                      \
        emacs                                    \
        -batch                                   \
        -l ~/.emacs.d/init.el                    \
        --eval "(run-hooks 'emacs-startup-hook)" \
        --eval '(euandreh/elfeed-batch-update)'
