#!/bin/sh
# Description: dmenu/rofi wrapper around sxbm
# Dependency: sxbm, dmenu/rofi, xclip (optional)
#
# Author: NRK
## Copyright 2021 NRK
## Licensed under GPL v3. See LICENSE for more details.
# Change "dmenu" to "rofi -dmenu" if you wish to use rofi
# NOTE: i do not use rofi, and haven't tested if it works or not
prompt="dmenu -i -l 24"

bm_open() {
	link_num="$(sxbm ls -c "$@" | $prompt | cut -d ")" -f 1)"
	[ -n "$link_num" ] && sxbm open -f "$link_num"
}

bm_yank() {
	link="$(sxbm ls -c "$@" | $prompt | cut -d " " -f 2)"
	[ -n "$link" ] && echo "$link" | xclip -in -selection clipboard
}

bm_add() {
	echo | $prompt -p "Add bookmark:" | xargs sxbm add | dmenu
}

bm_remove() {
	link_num="$(sxbm ls -c "$@" | $prompt | cut -d ")" -f 1)"
    link_title="$(sxbm ls -c | sed -n "${link_num}p" | cut -d ' ' -f 3)"
	[ -n "$link_num" ] && printf "y\nn" | $prompt -p "Delete this link? $link_title" | sxbm rm "$link_num"
}

case "$1" in
"-a"|"--add")
	shift && bm_add "$@"
;;
"-y"|"--yank")
	shift && bm_yank "$@"
;;
"-r"|"--remove")
	shift && bm_remove "$@"
;;
*)
	bm_open "$@"
;;
esac
