#!/bin/sh
set -eu

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

# wybierz JEDNO:
bookmark="$(xclip -o -selection primary 2>/dev/null || true)"     # zaznaczenie myszką
# bookmark="$(xclip -o -selection clipboard 2>/dev/null || true)"    # Ctrl+C

# usuń końcowe nowe linie (częste przy kopiowaniu)
bookmark="$(printf '%s' "$bookmark" | sed -e 's/[[:space:]]\+$//')"

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

# literalne dopasowanie całej linii
if grep -Fxq -- "$bookmark" "$file"; then
  notify-send "Oops" "Already Bookmarked!"
  exit 0
fi

# edycja w dmenu: domyślnie pokazuje już wartość
bookmarkEdit="$(printf '%s' "$bookmark" | dmenu -p "Edit bookmark:")"

# jeśli ESC albo pusto -> użyj oryginału
if [ -z "${bookmarkEdit:-}" ]; then
  out="$bookmark"
else
  out="$bookmarkEdit"
fi

# zapisz jako nową linię
printf '%s\n' "$out" >> "$file"
notify-send "Bookmark added!" "$out is now saved to the file"

# bookmark="$(xclip -o)"
# file="${HOME}/.snippets"
# 
# if [ -z "$bookmark" ]
# then
# 	notify-send "No string highlighted!" "Please select a string to bookmark"
# 	exit 1
# else
# 	if grep -q "^$bookmark$" "$file"; then
# 		notify-send "Oops" "Already Bookmarked!"
# 	else
# 		bookmarkEdit=$(:|dmenu -p "Make changes to the bookmark: $bookmark" & sleep 0.1 && xdotool type $bookmark)
# 		if [ -z "$bookmarkEdit" ]
# 		then
# 			notify-send "Bookmark added!" "$bookmark is now saved to the file"
# 			echo "$bookmark" >> $file
# 		else
# 			notify-send "Bookmark added!" "$bookmarkEdit is now saved to the file"
# 			echo "$bookmarkEdit" >> "$file"
# 		fi
# 	fi
# fi
