#!/bin/sh -e
#
# ask-password - make it easy to ask for a password
#
# ---
# see: https://github.com/unixorn/tumult.plugin.zsh/blob/main/bin/ask-password

os=$(uname -s | tr '[:upper:]' '[:lower:]')

echo_stderr() {
  # send message to stderr. exclude >&2 if you dont want it that way
  printf '%s\n' "$1" >&2
}

fail() {
  echo_stderr "$1"
  # return a code specified by $2 or 1 by default
  exit "${2-1}"
}

info() {
  printf '%s\n' "$*" >&2
}

check_dependency() {
  if ! (builtin command -V "$1" >/dev/null 2>&1); then
    fail "Missing dependency: can't find $1 in your PATH"
  fi
}

only_run_on() {
  if [ "${os}" != "darwin" ]; then
    fail "This script only runs on $1, this machine is running ${os}"
  else
    info "${os} is valid..."
  fi
}

only_run_on darwin
check_dependency osascript

if [ -z "$1" ]; then
  prompt="Password:"
else
  prompt="$1"
fi
PW=$(
  osascript <<EOF
tell application "System Events"
  activate
  text returned of (display dialog "${prompt}" default answer "" with hidden answer)
end tell
EOF
)

printf '%s' "${PW}"
