#!/bin/sh -e
#
# script [commands] [options] [arguments...]
#
# what script does.
#
# commands:
#   [d]el  [name] - Delete a password entry.
#   [e]dit [name] - Edit a password entry with ${EDITOR:-vi}.
#   [g]it  [cmd]  - Run git command in the password dir.
#   [h]elp        - Display this message.
#   [l]ist        - List all entries.
#   [s]how [name] - Show password for an entry.
#
# options:
#   -h|--help     - Display this message
#   -b|--bash     - Just use the simple bash read (prompt, no echo, and no stars)
#   -s|--stars    - Force the use of the shell 'askpass_stars' loop, not systemd
#   -d|--debug    - In shell script version, echo the character codes recieved
#
# env vars:
#   password dir:     export PA_DIR=~/.local/share/pa/passwords
###
#
# example:
#   ( echo 'phrase'; printf '%s' "$1" ) |
#   openssl enc -aes-256-cbc -nosalt -pass stdin -base64 |
#   s/^\(........\)/Pwd\1/'
#
#####

# discover where the shell script resides
# PROGNAME=$(type "$0" | awk '{print $3}') # search for executable on path
PROGNAME=$(basename "$0")          # search for executable on path
PROGDIR=$(dirname "${PROGNAME}")   # extract directory of program
PROGNAME=$(basename "${PROGNAME}") # base name of program

# unset FUNCTION   # ensure these are not an environment variables
# unset function
#
# # FUNCTION START
# FUNCTION='Encrypted Function
# will be stored here by the script options'
# # FUNCTION END

usage() { # report error and synopsis line only
  echo >&2 "${PROGNAME}:" "$@"
  sed >&2 -n '1,2d; /^###/q; /^#/!q; /^#$/q; s/^#  */Usage: /p;' \
    "${PROGDIR}/${PROGNAME}"
  echo >&2 "For help use option -h|--help"
  exit 10
}
help() { # output full header comments as documentation
  sed >&2 -n '1d; /^###/q; /^#/!q; s/^#//; s/^ //; p' \
    "${PROGDIR}/${PROGNAME}"
  echo >&2 "For full documentation use  ${PROGNAME} --doc"
  exit 10
}
doc() { # output the full documentation comments
  sed >&2 -n '1d; /^#####/q; /^#/!q; s/^#*//; s/^ //; p' \
    "${PROGDIR}/${PROGNAME}"
  exit 10
}
warning() { # print a program warning
  echo >&2 "${PROGNAME}: Warning, $*"
}
error() { # just output an error condition and exit (no usage)
  echo >&2 "${PROGNAME}: Error: $*"
  exit 2
}

# option handling
while [ "$#" -gt 0 ]; do
  case "$1" in
    -\? | -h | -help | --help) # basic help
      help
      ;;
    -doc | --doc*) # whole manual
      doc
      ;;
    --) # forced end of user options
      shift
      break
      ;;
    -*)
      usage "Unknown option \"$1\""
      ;;
    *) # unforced end of user options
      break
      ;;
  esac
  shift # next option
done

[ "$#" -gt 1 ] && usage "Too many Arguments"
[ "$#" -ne 1 ] && usage "Missing Argument" # optional argument (adjust to suit)
