#!/bin/sh
# history clipboard daemon (encrypted with SQLCipher)
# Monitors clipboard changes and logs them to the database
DB_PATH="$HOME/.local/share/history/history.db"
KEY_FILE="$HOME/.local/share/history/.key"
LAST_HASH=""
# Load encryption key
if [ ! -f "$KEY_FILE" ]; then
echo "Encryption key not found. Run 'history-init' first." >&2
exit 1
fi
KEY=$(cat "$KEY_FILE")
log_clipboard() {
local content="$1"
local hash="$2"
# Escape single quotes for SQL
content=$(echo "$content" | sed "s/'/''/g")
sqlcipher "$DB_PATH" "PRAGMA key = '$KEY'; INSERT OR IGNORE INTO clipboard_history (content, content_type, hash) VALUES ('$content', 'text', '$hash');"
}
# Check for clipnotify, fall back to polling
if command -v clipnotify >/dev/null 2>&1; then
# Event-driven (more efficient)
while true; do
clipnotify
content=$(xclip -selection clipboard -o 2>/dev/null || echo "")
[ -z "$content" ] && continue
hash=$(echo "$content" | md5sum | cut -d' ' -f1)
[ "$hash" = "$LAST_HASH" ] && continue
LAST_HASH="$hash"
log_clipboard "$content" "$hash"
done
else
# Polling fallback (check every second)
while true; do
content=$(xclip -selection clipboard -o 2>/dev/null || echo "")
if [ -n "$content" ]; then
hash=$(echo "$content" | md5sum | cut -d' ' -f1)
if [ "$hash" != "$LAST_HASH" ]; then
LAST_HASH="$hash"
log_clipboard "$content" "$hash"
fi
fi
sleep 1
done
fi