]> git.armaanb.net Git - bin.git/blob - fortune
fortune: fix bug
[bin.git] / fortune
1 #!/usr/bin/sh -e
2 # Fortune implementation in awk
3
4 usage()
5 {
6     echo "fortune -- a simple awk/POSIX sh implementation of fortune"
7     echo ""
8     echo "\t-h, --help                   show this help message"
9     echo "\t-l, --list=\$FILE            list installed cookie files"
10     echo "\t-f=\$FILE, --file=\$FILE     specify path to cookie file"
11     echo "\t-c=\$FILE, --cookie=\$FILE   specify cookie file"
12 }
13
14 FILE="$(find /usr/share/fortune/ -type f -not -name '*.dat')"
15 while [ "$1" != "" ]; do
16   PARAM=`echo $1 | awk -F= '{print $1}'`
17   VALUE=`echo $1 | awk -F= '{print $2}'`
18   case $PARAM in
19       -h | --help)
20           usage
21           exit
22           ;;
23       -f | --file)
24           FILE=$VALUE
25           ;;
26       -c | --cookie)
27           FILE=/usr/share/fortune/$VALUE
28           ;;
29       -l | --list)
30         ls -1 /usr/share/fortune
31         exit
32         ;;
33       *)
34           echo "ERROR: unknown parameter \"$PARAM\""
35           usage
36           exit 1
37           ;;
38   esac
39   shift
40 done
41
42 awk '
43 BEGIN {
44   f++
45 }
46
47 $1 == "%" {
48   f++
49 }
50
51 {
52   sub("%", "")
53   fortunes[f] = fortunes[f] (length(fortunes[f])?"\n":"") $0
54 }
55
56 END {
57   "date +%N" | getline time
58   srand(time)
59   print fortunes[int(rand() * f-2) + 2]
60 }' $FILE