#!/bin/sh
#
# Purpose {{{
# This script will :
#   1. If non gpg-key is in cache.
#     a. Run a terminal with a tmux splits (at least a split to enter gpg passphrase).
#     b. Wait until timeout.
#     c. Check every second if a key is now cached.
#     d. Kill dedicated terminal emulator window.
#   2. (When) a gpg-key is finally cached, simply call the "real" rofi-pass.
#
# 2023-01-12
# }}}

# GPG command to check cache {{{
# 0 : No key in cache
# 1 : At leaste one key in cache
# }}}
gpg_agent_info=$(gpg-connect-agent 'keyinfo --list' /bye 2>/dev/null | awk 'BEGIN{CACHED=0} /^S/ {if($7==1){CACHED=1}} END{if($0!=""){print CACHED} else {print "none"}}')
# Terminal emulator and window title
TERM_TITLE="Authentication with tmux"

TIMEOUT=60
TIME=1

# If gpg-agent doesn't have any key in cache
if [ "${gpg_agent_info}" -eq 0 ]; then
	## Start a terminal emulator
	## Create new tmux splits to ask for gpg passphrase
	"${TERM_EMULATOR}" --title "${TERM_TITLE}" -e bash -c 'tmux source-file "${HOME}"/.tmux/splitAUTHENTICATION && tmux attach-session' &

	# Minimum time to enter my passphrases
	sleep 5

	# Wait until TIMEOUT
	while [ "${TIME}" -lt "${TIMEOUT}" ]; do
		gpg_agent_info=$(gpg-connect-agent 'keyinfo --list' /bye 2>/dev/null | awk 'BEGIN{CACHED=0} /^S/ {if($7==1){CACHED=1}} END{if($0!=""){print CACHED} else {print "none"}}')

		## If a gpg key is in cache {{{
		if [ "${gpg_agent_info}" -eq 1 ]; then
			echo "While loop − GPG in cache"
			### Leave the loop
			break
		## }}}
		## Still no key {{{
		else
			## Wait a second
			TIME=$((TIME + 1))
			sleep 1
		fi
		## }}}
	done

	### Kill any remaining window
	kill $(pgrep --newest --full "${TERM_TITLE}") 2>/dev/null

	## If a gpg key is finally in cache
	if [ "${gpg_agent_info}" -eq 1 ]; then
		# Then, call real rofi-pass
		"${HOME}"/repos/rofi-pass/rofi-pass
	else
		exit 1
	fi

# If gpg-agent already have a key in cache {{{
else
	# Then, call real rofi-pass
	"${HOME}"/repos/rofi-pass/rofi-pass
fi
# }}}