#!/bin/sh
set -eu

file="$HOME/.snippets"
mkdir -p "$(dirname "$file")"
touch "$file"

# Choose ONE source:
bookmark="$(xclip -o -selection primary 2>/dev/null || true)"    # mouse highlight
# bookmark="$(xclip -o -selection clipboard 2>/dev/null || true)" # Ctrl+C clipboard

# Strip trailing whitespace/newlines (common when copying)
bookmark="$(printf '%s' "$bookmark" | sed 's/[[:space:]]\+$//')"

if [ -z "$bookmark" ]; then
  notify-send "No string highlighted!" "Please select/copy a string to bookmark"
  exit 1
fi

# Duplicate check: strip tab-separated comments before comparing
if awk -F'\t' '{print $1}' "$file" | grep -Fxq -- "$bookmark"; then
  notify-send "Oops" "Already Bookmarked!"
  exit 0
fi

# Optionally edit the bookmark text before saving
bookmarkEdit="$(printf '%s' "$bookmark" | dmenu -p "Edit bookmark:")"
out="${bookmarkEdit:-$bookmark}"

# Optionally add a comment (shown in dmenu search, not pasted)
comment="$(printf '' | dmenu -p "Add comment (optional):")"

if [ -n "${comment:-}" ]; then
  line="$(printf '%s\t# %s' "$out" "$comment")"
else
  line="$out"
fi

printf '%s\n' "$line" >> "$file"
notify-send "Bookmark added!" "$out is now saved to the file"
