X-Git-Url: https://git.armaanb.net/?p=bin.git;a=blobdiff_plain;f=fortune;h=fde90857a6d61e6d17080364c1c9a470158f888a;hp=3c8529425df9112d94f5657a46b12a8f89fe6f15;hb=de04de76b18b76b616d813cfa00b118a3ea2d39b;hpb=e06b7c831ac07a505ae02a4d9958c41e9afc0786 diff --git a/fortune b/fortune index 3c85294..fde9085 100755 --- a/fortune +++ b/fortune @@ -1,55 +1,95 @@ #!/usr/bin/sh -e -# Fortune implementation in awk +# Fortune implementation in POSIX sh/awk -usage() -{ - echo "fortune -- a simple awk/POSIX sh implementation of fortune" - echo "" - echo "\t-h, --help show this help message" - echo "\t-l, --list=\$FILE list installed cookie files" - echo "\t-f=\$FILE, --file=\$FILE specify path to cookie file" - echo "\t-c=\$FILE, --cookie=\$FILE specify cookie file" +usage() { + echo 'Usage: fortune [OPTIONS] +a simple POSIX sh/awk implementation of fortune + + -h, --help show this help message + -l, --list list installed cookie files + -c FILE, --cookie FILE specify cookie file + -n LENGTH, --min LENGTH specify min fortune length + -N LENGTH, --max LENGTH specify max fortune length + + fortune looks for fortunes in $FORTUNEDIR, which defaults to + /usr/share/fortune. + +Exit codes: + 0 success + 1 generic error + 2 argument parsing error' } -FILE="$(find /usr/share/fortune/ -type f -not -name '*.dat')" +parse_err() { + echo "$1" + $2 + exit 2 +} + +DIR=${FORTUNEDIR:-"/usr/share/fortune/"} +FILE="$(find $DIR -type f -not -name '*.dat')" +MAXLENGTH=1000000000000 +MINLENGTH=0 + while [ "$1" != "" ]; do - PARAM=`echo $1 | awk -F= '{print $1}'` - VALUE=`echo $1 | awk -F= '{print $2}'` - case $PARAM in - -h | --help) - usage - exit - ;; - -f | --file) - FILE=$VALUE - ;; - -c | --cookie) - FILE=/usr/share/fortune/$VALUE - ;; - -l | --list) - ls -1 /usr/share/fortune - exit - ;; - *) - echo "ERROR: unknown parameter \"$PARAM\"" - usage - exit 1 - ;; + case $1 in + -h | --help) + usage + exit + ;; + -c | --cookie) + FILE=$DIR/$2 + ;; + -n | --min) + MINLENGTH=$2 + ;; + -N | --max) + MAXLENGTH=$2 + ;; + -l | --list) + ls -1 $DIR + exit + ;; + *) + parse_err "ERROR: unknown option \"$1\"" usage + ;; esac - shift + shift 2 done -awk '$1 == "%" { - sub(/%/, "") - ++f +[ "$MAXLENGTH" -lt "$MINLENGTH" ] && { + parse_err "ERROR: maximum length is less than minimum length" +} + +[ -d "$FILE" ] && { + parse_err "ERROR: directory given, please provide a file or glob of files" +} + +[ "$(find $FILE -maxdepth 1 -print -quit 2> /dev/null)" ] || { + parse_err "ERROR: no such file or directory" +} + +awk -v maxlen=$MAXLENGTH -v minlen=$MINLENGTH \ +'BEGIN { + f++ +} + +$1 == "%" { + len = length(fortunes[f]) + if ( len>maxlen || len