unixorn/tumult.plugin.zsh

View on GitHub
bin/keychainctl

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash
#
# Original source: https://gist.github.com/AriaFallah/fe7b651ba2652bd301334e011749e4b2/

KEYCHAIN=${KEYCHAIN:-"secrets.keychain"}

if [[ "$(uname -s)" != 'Darwin' ]]; then
  echo 'Sorry, this script only works on macOS'
  exit 1
fi

main () {
  if [[ -z "$1" ]]; then
    print_usage
  fi

  case "$1" in
    ls) list_secrets ;;
    get) get_secret "$2" ;;
    set) set_secret "$2" "$3" ;;
    rm) delete_secret "$2" ;;
    *) print_usage ;;
  esac
}

list_secrets() {
  security dump-keychain "$KEYCHAIN" | grep 0x00000007 | awk -F= '{print $2}' | tr -d \"
}

get_secret() {
  if [[ -z "$1" ]]; then
    print_usage
  fi
  security find-generic-password -a "$USER" -s "$1" -w "$KEYCHAIN"
}

set_secret() {
  if [[ -z "$1" ]] || [[ -z "$2" ]]; then
    print_usage
  fi
  security add-generic-password -D secret -U -a "$USER" -s "$1" -w "$2" "$KEYCHAIN"
}

delete_secret() {
  if [[ -z "$1" ]]; then
    print_usage
  fi
  security delete-generic-password -a "$USER" -s "$1" "$KEYCHAIN"
}

print_usage() {
  NAME=$(basename "$0")
  cat << EOF
Usage:
  $NAME set <name> <value>
  $NAME get <name>
  $NAME rm <name>
  $NAME ls
EOF
  exit 0
}

# shellcheck disable=SC2068
main $@