#!/bin/bash
# list, put/get/delete ID

USAGE="Usage: \t$0 list\n\t$0 {put|get|delete} ID\n";

bailout () 
{
    echo -e "$@" >&2 
    exit 1
}

CMD=$1
if [ -z "$CMD" ] || [ "$CMD" != "put" -a "$CMD" != "get" \
	-a "$CMD" != "delete" -a "$CMD" != "list" ]; then
    bailout $USAGE
fi

if [ $CMD = "list" ]; then
    keyctl list @u |grep user: | cut -f 1,3 -d :
    exit $?
else
    ID=$2
    [ -z "$ID" ] && bailout "$CMD: missing ID argument\n"$USAGE

    if [ "$CMD" = "get" ]; then
	KID=$(keyctl request2 user $ID $ID @u 2>/dev/null)
	[ $? -ne 0 -o -z "$KID" ] && bailout "$CMD: requesting key failed"
	
	if [ -t 1 ];  then
	    bailout "secret available, but I won't print it to a tty\n"
	else
	    keyctl print $KID
	    exit $?
	fi
    elif [ "$CMD" = "put" ]; then
	if [ -t 0 ] ; then
	    if read -res -p "Enter secret to store under \"$ID\": " KEY </dev/tty; then
		KID=$(echo -n $KEY | /bin/keyctl padd user $ID @u )
	    fi
	else
	    # pipeline
	    KID=$(/bin/keyctl padd user $ID @u)
	    [ -z "$KID" ] && bailout "$CMD: adding key failed\n"
	fi
    elif [ "$CMD" = "delete" ]; then
	KID=$(keyctl search @u user $ID 2>/dev/null)
	[ $? -ne 0 -o -z "$KID" ] && bailout "$CMD: no such key \"$ID\"\n" 
	keyctl unlink $KID @u
	exit $?
    fi
fi
exit 0