#!/bin/bash
# recolic local secret management. Run this script to read a saved secret.
# note: secret name should not contain ':' or ' '

function die () { echo "RSEC error:" "$@" 1>&2 ; exit 1 ;  }

# legacy secret name support: trim leading prefix if any
_key=$(echo "$1" | sed 's/^R_SEC_//')

NEXTCLOUD_PREFIX=$HOME/$(ls $HOME | grep -i nextcloud)
RSEC_ENC_DB="$NEXTCLOUD_PREFIX/RSEC.gpg"
[[ ! -f "$RSEC_ENC_DB" ]] && die "ENC_DB missing"

RSEC_LINS="$(gpg -d "$RSEC_ENC_DB")" || die "gpg decrypt failure"
if [[ "$_key" = "" ]]; then
    echo "$RSEC_LINS" | cut -d : -f 1 | tr -d ' ' | grep -v '^#' | grep .
else
    RSEC_LINE="$(echo "$RSEC_LINS" | grep -i "^$_key *:")" || die "gpg decrypt failure or key not found"
    echo "$RSEC_LINE" | sed 's/^[^:]*://'
fi
exit $?
