]> git.armaanb.net Git - bin.git/blobdiff - fortune
fortune: fix bug
[bin.git] / fortune
diff --git a/fortune b/fortune
index 02276e6ecf76e4b612583e6a397668312494d1c2..8d1ed43f441b63d798502811a19b1c7277982666 100755 (executable)
--- a/fortune
+++ b/fortune
@@ -1,22 +1,60 @@
-#!/usr/bin/awk -f
+#!/usr/bin/sh -e
 # Fortune implementation in 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"
+}
+
+FILE="$(find /usr/share/fortune/ -type f -not -name '*.dat')"
+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
+          ;;
+  esac
+  shift
+done
+
+awk '
 BEGIN {
-  "date +%N" | getline time
-  srand(time)
-  "grep '%' " ARGV[1] " | wc -l" | getline n
-  line = int(rand() * n)
+  f++
 }
 
-/%/ {
-  if (p) {
-    exit
-  }
-  z++
-  next
+$1 == "%" {
+  f++
 }
 
-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) + 2]
+}' $FILE