#!/bin/sh -e
#
# pinentry-readline - read line securely via GnuPG's pinentry(1), print to stdout
#
# usage:
#     pinentry-readline </dev/null
#     echo [INPUT_FOR_PINENTRY] | [env PINENTRY_PROGRAM=pinentry-gtk-2] \
#        pinentry-readline [ARGS_FOR_PINENTRY]
#
# ---
# see: https://github.com/sunaku/home

is-linux && PINENTRY_PROGRAM=${PINENTRY_PROGRAM:-pinentry-curses}
is-mac && PINENTRY_PROGRAM=${PINENTRY_PROGRAM:-pinentry-mac}

{
  cat
  echo GETPIN
} | ${PINENTRY_PROGRAM} "$@" | awk '
  {
    if ($1 == "D") {
      print substr($0, 3)
    }
    else {
      print > "/dev/stderr"
    }
  }
  END { exit $1 != "OK" }
'
