summaryrefslogtreecommitdiff
path: root/os1eindopdracht/uhm
blob: 6624b6b48f553c1ba5e54f428a58cbe4fb693074 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/sh
WORD=""
DICT="/usr/share/dict/words"
ARGC=0

usage() {
	cat << EOF
usage: $0 [-h] [-w word] [-d file]

options:
  -w    set word to \`word\`
  -d    read dictionary from \`file\` ($DICT by default)
  -h    show help
EOF
  exit $1
}

while getopts d:w:h OPT; do
	[ $OPTIND -gt $ARGC ] && ARGC=$OPTIND
	case $OPT in
		h) usage 0 ;;
		w) WORD=$OPTARG ;;
		d) DICT=$OPTARG ;;
		\?|*) usage 1 ;;
	esac
done

if [ -z "$WORD" ]; then
	# check if dictionary file exists
	[ ! -e "$DICT" ] && echo "dictionary file doesn't exist!" && exit 1
	# check if dictionary file is a regular file (not directory, block device, etc.)
	[ ! -f "$DICT" ] && echo "dictionary file isn't a regular file!" && exit 1
	# check if dictionary file contains at least one line
	[ ! "`wc -l "$DICT" | cut -d' ' -f1`" -gt "0" ] && echo "dictionary file is empty!" && exit 1

	# filter words containing apostrophe or space, or words longer than 12 characters
	WORD="`sed -e "/[' ]/d" -e '/.\{13\}/d' "$DICT" | sort -R | head -n1`"
	# check if word is empty
	[ -z "$WORD" ] && echo "no usable words found in dictionary" && exit 1
fi

# convert word to lowercase
WORD="`echo "$WORD" | tr '[:upper:]' '[:lower:]'`"

pre_exit() {
	trap - EXIT # prevent double exit trigger
	echo ""
	echo "the word was $WORD"
	exit
}

# run pre_exit function on interrupt (Ctrl-C)
trap pre_exit INT

# main game loop (written in awk)
tput clear # clear screen
tput cup `stty size | cut -f1 -d' '` # move cursor to bottom left corner
$0.awk -vword="$WORD"
pre_exit