]> git.armaanb.net Git - bin.git/blobdiff - fortune
Remove unnecessary bash shebangs
[bin.git] / fortune
diff --git a/fortune b/fortune
index 02276e6ecf76e4b612583e6a397668312494d1c2..a8589a5f9e6a5ba8c4af5d12501becaf16c7270e 100755 (executable)
--- a/fortune
+++ b/fortune
@@ -1,22 +1,89 @@
-#!/usr/bin/awk -f
-# Fortune implementation in awk
+#!/usr/bin/sh -e
+# Fortune implementation in POSIX sh/awk
 
-BEGIN {
-  "date +%N" | getline time
-  srand(time)
-  "grep '%' " ARGV[1] " | wc -l" | getline n
-  line = int(rand() * n)
+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    argument error
+  2    parse error'
+}
+
+DIR=${FORTUNEDIR:-"/usr/share/fortune/"}
+FILE="$(find $DIR -type f -not -name '*.dat')"
+MAXLENGTH=1000000000000
+MINLENGTH=0
+
+while [ "$1" != "" ]; do
+  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
+      ;;
+    *)
+      echo "ERROR: unknown option \"$1\""
+      usage
+      exit 1
+      ;;
+  esac
+  shift 2
+done
+
+[ "$MAXLENGTH" -lt "$MINLENGTH" ] && {
+  echo "ERROR: maximum length is less than minimum length"
+  exit 2
+}
+
+[ -d "$FILE" ] && {
+  echo "ERROR: directory given, please provide a file or glob of files"
+  exit 2
+}
+
+awk -v maxlen=$MAXLENGTH -v minlen=$MINLENGTH \
+'BEGIN {
+  f++
 }
 
-/%/ {
-  if (p) {
-    exit
+$1 == "%" {
+  len = length(fortunes[f])
+  if ( len>maxlen || len<minlen ) {
+    fortunes[f] = ""
+  } else {
+    f++
   }
-  z++
-  next
 }
 
-z == line {
-  print $0
-  p = 1
+{
+  sub("%", "")
+  fortunes[f] = fortunes[f] (length(fortunes[f])?"\n":"") $0
 }
+
+END {
+  "date +%N" | getline time
+  srand(time)
+  print fortunes[int(rand() * (f - 2)) + 1]
+}' $FILE