summary refs log tree commit diff
path: root/bin/secretmenu
blob: 8c447fbc43ae684ae552af71c0c43ecd9f9d2992 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/bin/bash

set -eo pipefail
[ -n "$DEBUG" ] && set -x

ico=$(iconez -fs -n dialog-password-symbolic)
trap '{ notify-send -a secretmenu -i "${ico}" -c error "secretmenu: failed :(" "<i>pipefail</i>"; exit 1; }' ERR

secretmgr=rbw
printpass=
while getopts bpPh name; do
	case ${name} in
	b) secretmgr=rbw ;;
	p) secretmgr=pass ;;
	P) printpass=1 ;;
	h | ?)
		echo "usage: secretmenu [-bp] [-P] [query]"
		echo
		exit 2
		;;
	esac
done
shift $((OPTIND - 1))

# check requirements
for tool in bemenu fd flock fzf $secretmgr; do
	if ! command -v "$tool" >/dev/null; then
		printf "%s: %s not installed but required\n" "$(basename "$0")" "$tool" >&2
		exit 1
	fi
done

# ensure only one menu runs at a time
lockfile="$XDG_RUNTIME_DIR"/secretmenu.lock
[ "$FLOCKER" != "$lockfile" ] && exec env FLOCKER="$lockfile" flock -ew 30 "$lockfile" "$0" "$@"
trap '{ env UNSAFE=1 rm $lockfile 2>/dev/null || true; }' EXIT TERM INT

__menu() {
	if [ -t 1 ]; then
		echo "terminal mode not implemented"
		exit 1
	fi
	MENU_PROMPT="󰌆 secret" menu --list=10 --accept-single ${@:+--filter "$@"}
}

if [ "$secretmgr" = "rbw" ] && command -v rbw >/dev/null 2>&1; then
	__list_secrets() {
		rbw list --fields name,user,folder,id | column -t -s $'\t'
	}
	__query_secret() {
		# query by the last space-separated item (id)
		rbw get --full -- "${1##* }" 2>&1
	}
fi
if [ "$secretmgr" = "pass" ] && command -v pass >/dev/null 2>&1; then
	__list_secrets() {
		prefix=${PASSWORD_STORE_DIR-~/.password-store}
		prefix=$(readlink -f -- "${prefix}")
		fd -e gpg . "${prefix}" |
			sed -e "s#${prefix}/##" -e 's#\.gpg$##'
	}
	__query_secret() {
		pass show "$1" 2>&1
	}
fi

if [ -n "$printpass" ]; then
	__handle() {
		awk 'NR==1 {print $0;hit+=1} END{if(hit==0){print("no secret found") >/dev/stderr; exit(1);}}'
	}
else
	__handle() {
		awk 'NR==1 {system("wl-copy -n " $0);hit+=1} /^Username:/ {system("wl-copy -n -p " $2);hit+=1} END{if(hit==0){print("no secret found") >/dev/stderr; exit(1);}}'
	}
fi

# main

pw=$({
	__list_secrets
	echo ">>pass"
	echo ">>rbw"
} |
	__menu "$@")

case "$pw" in
"") exit 1 ;;
">>pass") exec "$0" -p ;;
">>rbw") exec "$0" -b ;;
esac

__query_secret "$pw" | __handle
__ok=$?

[ -n "$printpass" ] && exit "$__ok"

if [ "$__ok" -eq 0 ]; then
	notify-send \
		-a secretmenu \
		-i "${ico}" \
		'secretmenu: secret copied' \
		'<i>will be removed after next paste</i>'
else
	notify-send \
		-a passmenu \
		-i "${ico}" \
		-c error \
		'secretmenu: failed :(' \
		"<i>check stderr for details</i>"
	exit 1
fi