]> git.armaanb.net Git - bin.git/blob - fortune
a8589a5f9e6a5ba8c4af5d12501becaf16c7270e
[bin.git] / fortune
1 #!/usr/bin/sh -e
2 # Fortune implementation in POSIX sh/awk
3
4 usage() {
5   echo 'Usage: fortune [OPTIONS]
6 a simple POSIX sh/awk implementation of fortune
7
8   -h, --help                    show this help message
9   -l, --list                    list installed cookie files
10   -c FILE, --cookie FILE        specify cookie file
11   -n LENGTH, --min LENGTH       specify min fortune length
12   -N LENGTH, --max LENGTH       specify max fortune length
13
14   fortune looks for fortunes in $FORTUNEDIR, which defaults to
15   /usr/share/fortune.
16
17 Exit codes:
18   0    success
19   1    argument error
20   2    parse error'
21 }
22
23 DIR=${FORTUNEDIR:-"/usr/share/fortune/"}
24 FILE="$(find $DIR -type f -not -name '*.dat')"
25 MAXLENGTH=1000000000000
26 MINLENGTH=0
27
28 while [ "$1" != "" ]; do
29   case $1 in
30     -h | --help)
31       usage
32       exit
33       ;;
34     -c | --cookie)
35       FILE=$DIR/$2
36       ;;
37     -n | --min)
38       MINLENGTH=$2
39       ;;
40     -N | --max)
41       MAXLENGTH=$2
42       ;;
43     -l | --list)
44       ls -1 $DIR
45       exit
46       ;;
47     *)
48       echo "ERROR: unknown option \"$1\""
49       usage
50       exit 1
51       ;;
52   esac
53   shift 2
54 done
55
56 [ "$MAXLENGTH" -lt "$MINLENGTH" ] && {
57   echo "ERROR: maximum length is less than minimum length"
58   exit 2
59 }
60
61 [ -d "$FILE" ] && {
62   echo "ERROR: directory given, please provide a file or glob of files"
63   exit 2
64 }
65
66 awk -v maxlen=$MAXLENGTH -v minlen=$MINLENGTH \
67 'BEGIN {
68   f++
69 }
70
71 $1 == "%" {
72   len = length(fortunes[f])
73   if ( len>maxlen || len<minlen ) {
74     fortunes[f] = ""
75   } else {
76     f++
77   }
78 }
79
80 {
81   sub("%", "")
82   fortunes[f] = fortunes[f] (length(fortunes[f])?"\n":"") $0
83 }
84
85 END {
86   "date +%N" | getline time
87   srand(time)
88   print fortunes[int(rand() * (f - 2)) + 1]
89 }' $FILE