#!/usr/bin/env bash

PASSWORDS="$HOME/.password-store"

extraArgs=""

hostname | grep -q 'phone' && extraArgs="-normal-window"

function type_password(){
	local password="$1"
	local pw=$(pass "$password" | head -n 1)
	if [ -z "$pw" ]; then
		exit 1
	fi
	sleep 1
	# xdotool doesn't appear to like it if I am uring colemak
	# To get around that, switch back to normal
	setxkbmap -layout gb
	echo "$pw" |  xdotool type --clearmodifiers --file -
	# Then revert back to colemak
	setxkbmap -layout gb,gb -variant "colemak," -option grp:shifts_toggle
	xset r rate 200 70
	xinput --list | grep -Ei 'ErgoDox EZ\s+id' | grep -oE 'id=[0-9]+' | cut -d'=' -f2 | xargs -r setxkbmap -layout gb -device
}
function copy_password(){
	local password="$1"
	local part="${2:-0}"
	local sleep_argv0="jh password store sleep on display $DISPLAY"
	local before="$(xclip -o -selection clipboard 2>/dev/null | base64)"
	pkill -f "^$sleep_argv0" 2>/dev/null && sleep 0.5
	local pw=""
	case "$part" in
		"10"|"otp")
			local pw=$(pass otp "$password" | head -n 1)
			;;
		*)
			local pw=$(pass "$password" | head -n 1)
			;;
	esac
	if [ -z "$pw" ]; then
		exit 1
	fi
	echo "$pw" | xclip -selection "primary"
	echo "$pw" | xclip -selection "clipboard"
	notify-send -t 3000 "Password put on clipboard" "Will be removed in 3 seconds"
	(
		( exec -a "$sleep_argv0" bash <<<"trap 'kill %1' TERM; sleep '3' & wait" )

		echo "$before" | base64 -d | xclip -selection "primary"
		echo "$before" | base64 -d | xclip -selection "clipboard"

		notify-send "Password Clearerd"

	) >/dev/null 2>&1 & disown
}

if [ -d "$PASSWORDS" ]; then
	cd "$PASSWORDS"
	selection="$1"
	ret="${2:-0}"
	if [ -z "$selection" ]; then
		selection=$(find . -type f -name '*.gpg' | sed 's/.gpg$//' | sed 's/^.\///' | rofi -dmenu -kb-custom-1 "Ctrl-o" -kb-custom-2 "Ctrl-i" -i -l 20 $extraArgs)
		ret="$?"
	fi
	if [ -n "$selection" ]; then
		if [[ "$selection" == "NEW" ]]; then
			dir="$(find . -type d -not -path \*.git\* |rofi -dmenu -p Directory | sed 's/^.\/?//')"
			if [ ! -d "$dir" ]; then
				mkdir -p "$dir"
			fi
			name="$(rofi -dmenu -p Name -lines 0)"
			# Todo - create new passwords
		else
			if [ "$ret" -ne "11" ]; then
				copy_password "$selection" "$ret"
			else
				type_password "$selection" "$ret"
			fi
		fi
	fi
else
	notify-send "\$PASSWORDS doesn't exist"
fi
