summary refs log tree commit diff stats
path: root/thesauracles
blob: 218cf887046f170575680a1c5f52657d915d29d9 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env bash
# THESAURACLES -- synonym oracle
# Copyright (C) Case Duckworth <acdw@acdw.net>
# with thanks to Will Sinatra

### Commentary:

## The wise Thesauracles has the synonym you seek!
# Ask Thesauracles about a word you'd like to synonymize.
# He will think about the word and all the others nearby it, before finally
# yelling out the perfect synonym.

## Usage:
# thesauracles <word>

### Code:

wf=/tmp/thesauracles
dict_server="dict.org"
dict_database="moby-thesaurus"
thesaurus_header_lines=3

usage() {
	cat <<EOF
thesauracles: the wise sage of synonyms

USAGE:
	thesauracles -h
	thesauracles [OPTIONS] WORD

FLAGS:
 -h	Show this help
 -q	Be quiet (only exclaim the final word).

OPTIONS:
 -c DEGREE	The DEGREE of creativity Thesauracles should use.
		Higher creativity means a more interesting synonym.
		Default: $degree.
 -s SERVER	Specify the dict:// SERVER to use.
		Default: $dict_server.
 -t THESAURUS	Specify the dict:// THESAURUS to use.
		Default: $dict_database.
 -l LINES	Number of LINES to skip from the server output.
		Might need to change this if you change the server.
		Default: $thesaurus_header_lines.
EOF
	exit ${1:-0}
}

query() {
	response="/tmp/$1.thesauracles"
	if [ ! -f "$response" ]; then
		curl "dict://$dict_server/d:$1:$dict_database" >"$response" 2>/dev/null
	else
		sleep 0.3
	fi
	if grep -q 552 "$response"; then
		return 1
	fi
	sed -n '/^151/,/^.$/p' "$response" |
		tail -n+$thesaurus_header_lines |
		awk 'BEGIN{RS=","}{sub(/^[ \n\t\r]+/,"");print}' >"$wf"
}

random_word() {
	sort -Ru "$wf" | head -n1
}

main() {
	degree=6 # the Kevin Bacon number ;)
	talkative=true

	while getopts hqc:s:t:h: opt; do
		case "$opt" in
		h) usage ;;
		q) talkative=false ;;
		c) degree="$OPTARG" ;;
		s) dict_server="$OPTARG" ;;
		t) dict_database="$OPTARG" ;;
		l) thesaurus_header_lines="$OPTARG" ;;
		*) usage 1 ;;
		esac
	done
	shift $((OPTIND - 1))

	word="$1"
	words=()
	hopn=0
	while [ "$hopn" -lt "$degree" ]; do
		#printf '%s ' "$hopn"
		if query "$word"; then
			$talkative && echo "$word..." >&2
			words+=("$word")
			word="$(random_word)"
			: $((hopn++))
		elif [ "$hopn" -eq 0 ]; then
			echo "Oops, don't know \"$word!\"" >&2
			exit 2
		else
			$talkative && echo "hmm." >&2
			: $((hopn--))
			word="${words[-1]}"
		fi
	done
	echo "$word" |
		if $talkative; then
			awk '{print "> " toupper($0) "!"}'
		else
			cat
		fi
}

if [[ "$BASH_SOURCE" = "$0" ]]; then
	main "$@"
fi