#!/usr/bin/env mksh
# $MirOS: contrib/hosted/tg/code/kwalletcli/kwalletaskpass,v 1.3 2009/07/09 19:18:24 tg Exp $
#-
# Copyright © 2009
#	Thorsten Glaser <tg@mirbsd.org>
#
# Provided that these terms and disclaimer and all copyright notices
# are retained or reproduced in an accompanying document, permission
# is granted to deal in this work without restriction, including un‐
# limited rights to use, publicly perform, distribute, sell, modify,
# merge, give away, or sublicence.
#
# This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
# the utmost extent permitted by applicable law, neither express nor
# implied; without malicious intent or gross negligence. In no event
# may a licensor, author or contributor be held liable for indirect,
# direct, other damage, loss, or other issues arising in any way out
# of dealing in the work, even if advised of the possibility of such
# damage or existence of a defect, except proven that it results out
# of said person’s immediate fault when using the work as intended.

unset LC_ALL LANGUAGE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES \
    LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION
export LANG=C LC_CTYPE=en_US.UTF-8
set -U

if (( $# != 1 )); then
	print -u2 wrong number of arguments
	exit 127
fi

rv=1
trywallet=0
if [[ $1 = @(Enter passphrase for )* ]]; then
	trywallet=1
	pw=$(kwalletcli -q -f kwalletaskpass -e "${1#Enter }")
	rv=$?
fi

if (( rv )); then
	pw=$(kwalletcli_getpin -q -t "$1")
	rv=$?
	if (( rv == 0 && trywallet )); then
		q=${1#Enter }
		q=${q%%:*([	 ])}
		kwalletcli_getpin -qb -t "Store $q in the KDE Wallet?" && \
		    kwalletcli -q -f kwalletaskpass -e "${1#Enter }" -p "$pw"
	fi
fi

case $rv {
(0)	print -r -- "$pw"
	exit 0 ;;
(1)	exit 1 ;;
(*)	exit 3 ;;
}
