#!/usr/bin/env bash
# rofi-bookmarks: pick a Chromium bookmark and open it (new tab or new window)

set -euo pipefail
awesome-client 'show_dim()' >/dev/null 2>&1
trap 'awesome-client "hide_dim()" >/dev/null 2>&1' EXIT

BOOKMARKS_FILE="$HOME/.config/chromium/Default/Bookmarks"

if [ ! -f "$BOOKMARKS_FILE" ]; then
    notify-send "Bookmarks" "Chromium bookmarks file not found"
    exit 1
fi

# Recursively walk the bookmark tree (roots -> bookmark_bar / other / synced)
# and emit "title\turl" for every leaf ("type": "url"), skipping folders.
list=$(jq -r '
    def walk_nodes:
        if .type == "url" then
            "\(.name)\t\(.url)"
        elif .children then
            .children[] | walk_nodes
        else
            empty
        end;
    .roots | to_entries[] | .value | walk_nodes
' "$BOOKMARKS_FILE")

if [ -z "$list" ]; then
    notify-send "Bookmarks" "No bookmarks found"
    exit 0
fi

chosen=$(echo "$list" | awk -F'\t' '{print $1}' | rofi -dmenu -i -p "Bookmarks" \
    -theme-str 'listview { lines: 5; }' \
    -theme-str 'window { width: 21%; }' \
    -theme-str 'window { height: 400px; }')

[ -z "$chosen" ] && exit 0

url=$(echo "$list" | awk -F'\t' -v title="$chosen" '$1 == title { print $2; exit }')

[ -z "$url" ] && exit 0

# Open in a new tab of the existing Chromium window if one's running,
# otherwise this also launches Chromium fresh with that tab.
chromium --new-tab "$url"
