#!/bin/sh set -o errexit set -o nounset readonly EXIT_SUCCESS=0 readonly SECRETS_DIR_BASE="${HOME}/.secrets" cmd_help() { echo "USAGE key script for store secrets key list - Show list secrets key get (SECRET) - Show secret content key set (SECRET) - Add secret (read content from stdin or from args or from EDITOR) key edit (SECRET) - Edit secret with INDEX by \$EDITOR key delete (SECRET) [SECRET] ... - Delete secrets key --help - Show this message" } die() { echo "$(basename "${0}"): Error: ${1}" 1>&2 exit "${2:-${EXIT_SUCCESS}}" } cmd_set_secret() { secret_to_add="${SECRETS_DIR_BASE}/${1}"; shift if read -t 0 _; then cat > "${secret_to_add}" elif [ -n "$*" ]; then echo "$*" > "${secret_to_add}" else ${EDITOR} "${secret_to_add}" fi exit "${EXIT_SUCCESS}" } cmd_delete_secret() { for secret in "$@" do secret_to_remove="${SECRETS_DIR_BASE}/${secret}" if [ ! -f "${secret_to_remove}" ]; then die "Secret '${secret}' not found" 1 fi rm "${secret_to_remove}" done exit "${EXIT_SUCCESS}" } cmd_edit_secret() { secret="${1}" secret_to_edit="${SECRETS_DIR_BASE}/${secret}" if [ ! -f "${secret_to_edit}" ]; then die "Secret '${secret}' not found" 1 fi ${EDITOR} "${secret_to_edit}" exit "${EXIT_SUCCESS}" } cmd_get_secret() { secret="${1}" secret_to_cat="${SECRETS_DIR_BASE}/${secret}" if [ ! -f "${secret_to_cat}" ]; then die "Secret '${secret}' not found" 1 fi cat "${secret_to_cat}" exit "${EXIT_SUCCESS}" } cmd_list_secrets() { ls "${SECRETS_DIR_BASE}" } if [ ! -d "${SECRETS_DIR_BASE}" ]; then mkdir "${SECRETS_DIR_BASE}" fi if [ -z "${1+x}" ]; then cmd_help exit "${EXIT_SUCCESS}" fi case "${1}" in l|list) shift; cmd_list_secrets ;; s|set) shift; cmd_set_secret "$@" ;; g|get) shift; cmd_get_secret "$@" ;; d|delete) shift; cmd_delete_secret "$@" ;; e|edit) shift; cmd_edit_secret "$@" ;; --help) shift; cmd_help ;; *) cmd_help "$@" ;; esac exit "${EXIT_SUCCESS}"