default_lifetime='1d'

get_credentials()
{
    case $# in
    0) _args="[\"$default_lifetime\", []]" ;;
    1) _args="[\"$1\", []]" ;;
    2) _args="[\"$1\", \"$2\"]" ;;
    esac

    _response="$(erl_rpc 'eturnal_ctl' 'get_credentials' "$_args")"

    case $_response in
        '{ok,'*)
            echo "$_response" | sed -e 's/{ok, *"\(.*\)"}/\1/' -e 's/~n/\
/g'
            exit 0
            ;;
        '{error,'*)
            echo "$_response" | sed 's/{error, *"\(.*\)"}/\1/' >&2
            exit 1
            ;;
        *)
            echo "Unknown error: '$_response'" >&2
            exit 1
            ;;
    esac
}

if [ $# -ge 1 ] && [ "x$1" = 'xhelp' ]
then
    echo "Usage: $REL_NAME credentials [Expiry[s|m|h|d] [Suffix]]"
    echo 'Print credentials valid for the given Expiry period. An "m", "h", or'
    echo '"d" unit can be appended in order to specify the Expiry period in'
    echo 'minutes, hours, or days, respectively. The default unit is seconds.'
    echo 'Alternatively, the Expiry time can be specified as an RFC 3339'
    echo 'timestamp. If no Expiry is specified, the generated credentials'
    echo 'expire after 24 hours. If both an Expiry and a Suffix are specified,'
    echo 'the Suffix is appended to the generated user name, separated from the'
    echo 'expiration timestamp with a colon. If multiple secrets are'
    echo 'configured, the password is derived from the first one listed.'
    exit 0
elif [ $# -le 2 ]
then
    ping_or_exit
    get_credentials "$@"
else
    echo "Usage: $REL_NAME credentials [Expiry[s|m|h|d] [Suffix]]" >&2
    exit 2
fi
