env/bin/credentials.sh

134 lines
2.4 KiB
Bash

#!/bin/sh
# credentials
# Written in 2019 by Lucas
# CC0 1.0 Universal/Public domain - No rights reserved
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty. You should have received a copy of the CC0 Public Domain
# Dedication along with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.
usage()
{
cat - <<. >&2
Usage:
${0##*/} [-2pu] service
${0##*/} -r key
.
exit 1
}
err()
{
printf "%s: %s\n" "${0##*/}" "$*" >&2
exit 1
}
clip()
{
xclip -q -r -l 1 -sel clip 2>/dev/null
}
get_user()
{
printf user
sekrit get "services/$1/user" | clip && printf "\n"
}
get_pass()
{
printf pass
sekrit get "services/$1/pass" | clip && printf "\n"
}
get_2fa()
{
printf 2fa
otpcli_opts=
case $1 in
isnic) otpcli_opts="-H sha512 -d 8"
;;
esac
sekrit get "services/$1/2fa" | otpcli $otpcli_opts | clip && printf "\n"
}
get_service()
{
service=$1
user=$2
pass=$3
sfa=$4
if [ $user = no ] && [ $pass = no ] && [ $sfa = no ]; then
sekrit has "services/$service/pass" ||
err "Unknown service \"$service\"."
pass=yes
sekrit has services/"$service"/user && user=yes
sekrit has services/"$service"/2fa && sfa=yes
fi
if [ $user = check ]; then
sekrit has services/"$service"/user ||
err "Service \"$service\" has no user."
user=yes
fi
if [ $pass = check ]; then
sekrit has services/"$service"/pass ||
err "Service \"$service\" has no pass."
pass=yes
fi
if [ $sfa = check ]; then
sekrit has services/"$service"/2fa ||
err "Service \"$service\" has no 2fa."
sfa=yes
fi
[ $user = yes ] && get_user "$service"
[ $pass = yes ] && get_pass "$service"
[ $sfa = yes ] && get_2fa "$service"
}
get_raw()
{
key=$1
sekrit has "$key" || err "Unknown key \"$key\"."
printf "%s" "$key"
sekrit get "$key" | clip && printf "\n"
}
sfa=no
pass=no
raw=no
user=no
while getopts 2pru flag; do
case $flag in
2) sfa=check
;;
p) pass=check
;;
r) raw=yes
;;
u) user=check
;;
*) usage
;;
esac
done
shift $(($OPTIND - 1))
[ $# -eq 1 ] && [ -n "$1" ] || usage
key=$1
if [ $raw = yes ]; then
if [ $sfa != no ] || [ $pass != no ] || [ $user != no ]; then
err "-r is mutually exclusive with -2pu."
fi
get_raw "$key"
else
get_service "$key" $user $pass $sfa
fi