sekrit: small refactor

This commit is contained in:
Lucas 2020-12-02 03:40:50 +00:00
parent c2af544099
commit f500903cba

View File

@ -56,11 +56,21 @@ check_key()
esac esac
} }
make_key_path()
{
check_key "$1" && printf "%s/%s.gpg" "$SEKRIT_DIR" "$1"
}
to_number() to_number()
{ {
printf "%u" "$*" 2>/dev/null printf "%u" "$*" 2>/dev/null
} }
_sekrit_decrypt()
{
gpg2 -qd "$1"
}
sekrit_add() sekrit_add()
{ {
force=no force=no
@ -75,22 +85,24 @@ sekrit_add()
[ $# -ge 1 ] && [ -n "$1" ] || usage [ $# -ge 1 ] && [ -n "$1" ] || usage
key=$1 key=$1
check_key "$key"
shift shift
path=$(make_key_path "$key")
f=$SEKRIT_DIR/$key.gpg if [ -f "$path" ] && [ $force = no ]; then
mkdir -p "${f%/*}" err "key $key already exists"
fi
[ -f "$f" ] && [ $force = no ] && err "key $key already exists" path=$SEKRIT_DIR/$key.gpg
mkdir -p "${path%/*}"
if [ $# -gt 0 ]; then if [ $# -gt 0 ]; then
# use all additional parameters as a single string # use all additional parameters as a single string
printf "%s\n" "$*" printf "%s\n" "$*"
else else
cat - cat -
fi | gpg2 -qae -r "$SEKRIT_GPG_ID" >|"$f" fi | gpg2 -qae -r "$SEKRIT_GPG_ID" >|"$path"
# make it read-only # make it read-only
chmod -- 400 "$f" chmod -- 400 "$path"
} }
sekrit_cp() sekrit_cp()
@ -110,8 +122,9 @@ sekrit_cp()
[ $# -eq 1 ] || usage [ $# -eq 1 ] || usage
key=$1 key=$1
path=$(make_key_path "$key")
sekrit_has "$key" && sekrit_get "$key" | [ -f "$path" ] || err "no data for key $key"
_sekrit_decrypt "$path" |
xclip $rmlastnl -loops 1 -quiet -selection clip 2>/dev/null xclip $rmlastnl -loops 1 -quiet -selection clip 2>/dev/null
} }
@ -146,22 +159,17 @@ sekrit_get()
{ {
[ $# -eq 1 ] || usage [ $# -eq 1 ] || usage
key=$1 key=$1
check_key "$key" path=$(make_key_path "$key")
shift [ -f "$path" ] || err "no data for key $key"
_sekrit_decrypt "$path"
f=$SEKRIT_DIR/$key.gpg
[ -f "$f" ] || err "no data for key $key"
gpg2 -qd "$f"
} }
sekrit_has() sekrit_has()
{ {
[ $# -eq 1 ] || usage [ $# -eq 1 ] || usage
key=$1 key=$1
check_key "$key" path=$(make_key_path "$key")
shift [ -f "$path" ]
[ -f "$SEKRIT_DIR/$key.gpg" ]
} }
ls_key() ls_key()
@ -169,7 +177,7 @@ ls_key()
d=$SEKRIT_DIR$1 d=$SEKRIT_DIR$1
find "$d" -type f -name "*.gpg" | find "$d" -type f -name "*.gpg" |
sort | sort |
sed -e "s#^$d##" -e "s#\.gpg\$##" sed -e "s#^$d##" -e 's#\.gpg$##'
} }
sekrit_ls() sekrit_ls()
@ -179,7 +187,7 @@ sekrit_ls()
else else
for key; do for key; do
printf "%s:\n" "$key" printf "%s:\n" "$key"
ls_key /"$key"/ | sed "s/^/ /" ls_key "/$key/" | sed "s/^/ /"
printf "\n" printf "\n"
done done
fi fi