#!/bin/sh
# badphrase: generate passphrases or something lol
# diceware example: ./badphrase -dvl /tmp/diceware.wordlist.asc -w 10
# please use with diceware bacause all other wordlists suck ToT
# yay!
set -e

charmin=0
charmax=0
copy=0
diceware=0
entropymin=128
includenames=0
verbose=0
wordlist=/usr/share/dict/words
wordnum=8

usage() {
  echo "usage: ${0##*/} [-cdhiv] [-e entropymin] [-l wordlist] [-m charmax] \
[-n charmin] [-w wordnum]" 1>&2
}

while getopts cde:hil:m:n:vw: arg; do
  # shellcheck disable=SC2249
  case ${arg} in
    c) copy=1 ;;
    d) diceware=1 ;;
    e) entropymin=${OPTARG} ;;
    h)
      usage
      exit
      ;;
    i) includenames=1 ;;
    l) wordlist=${OPTARG} ;;
    m) charmax=${OPTARG} ;;
    n) charmin=${OPTARG} ;;
    v) verbose=1 ;;
    w) wordnum=${OPTARG} ;;
    ?)
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND - 1))
# setup regex
if [ "${includenames}" -eq 1 ]; then
  re_class='.'
else
  re_class='^[^A-Z]'
fi
[ "${charmin}" -lt 0 ] && charmin=0
[ "${charmax}" -le 0 ] && charmax=''
# password generation pipeline
# extract 2nd column if we're on a diceware list
awk -v diceware="${diceware}" 'BEGIN {
        if (diceware)
                rec = 2
        else
                rec = 1
}
{ print $rec }' "${wordlist}" \
  |
  # filter and shuffle the wordlist
  grep -x "${re_class}\{${charmin},${charmax}\}" | sort -R \
  |
  # test entropy against $entropymin and if that worked print first $wordnum lines
  { awk -v prog="${0##*/}" -v entropymin="${entropymin}" -v wordnum="${wordnum}" -v \
    verbose="${verbose}" 'NR <= wordnum { line[NR] = $0 }
END {
        perms = NR
        # show entropy
        entropy = log(perms^wordnum) / log(2)
        if (verbose)
                printf("log2(%d^%d) = %.2f bits of entropy\n", perms, wordnum, \
                        entropy) >"/dev/stderr"
        # stop if we dont satisfy entropy requirements
        lengthmin = log(2^entropymin) / log(perms)
        if (wordnum < lengthmin) {
                printf("%s: wordnum needs to be >= %.2f so that entropy would be \
                        >= %d\n",  prog, lengthmin, entropymin) >"/dev/stderr"
                exit 1
        } else {
                for (i = 1; i < wordnum; i++)
                        print line[i]
        }
}' || exit 1; } \
  |
  # output passphrase
  if [ "${copy}" -eq 1 ]; then
    paste -sd '' - | xclip -selection clipboard
  else
    paste -sd ' ' -
  fi
