diff options
-rwxr-xr-x | thesauracles | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/thesauracles b/thesauracles new file mode 100755 index 0000000..3891d18 --- /dev/null +++ b/thesauracles | |||
@@ -0,0 +1,60 @@ | |||
1 | #!/usr/bin/env bash | ||
2 | # THESAURACLES -- synonym oracle | ||
3 | # Copyright (C) Case Duckworth <acdw@acdw.net> | ||
4 | # with thanks to Will Sinatra | ||
5 | |||
6 | ### Commentary: | ||
7 | |||
8 | ### Code: | ||
9 | |||
10 | dict_server="dict.org" | ||
11 | dict_database="moby-thesaurus" | ||
12 | thesaurus_header_lines=3 | ||
13 | |||
14 | wf=/tmp/thesauracles | ||
15 | |||
16 | hops=3 | ||
17 | |||
18 | query() { | ||
19 | response="$(mktemp /tmp/thesauracles.XXXXXX)" | ||
20 | trap "rm -f $response" KILL | ||
21 | curl "dict://$dict_server/d:$1:$dict_database" >"$response" 2>/dev/null | ||
22 | if grep -q 552 "$response"; then | ||
23 | return 1 | ||
24 | fi | ||
25 | sed -n '/^151/,/^.$/p' "$response" | | ||
26 | tail -n+$thesaurus_header_lines | | ||
27 | awk 'BEGIN{RS=","}{sub(/^[ \n\t\r]+/,"");print}' >"$wf" | ||
28 | } | ||
29 | |||
30 | random_word() { | ||
31 | n="$(wc -l <"$wf")" | ||
32 | ln="$((RANDOM % n + 1))" | ||
33 | sed -n ${ln}p "$wf" | ||
34 | } | ||
35 | |||
36 | main() { | ||
37 | word="$1" | ||
38 | words=() | ||
39 | hopn=0 | ||
40 | while [ "$hopn" -lt "$hops" ]; do | ||
41 | if query "$word"; then | ||
42 | echo "$word..." | ||
43 | words+=("$word") | ||
44 | word="$(random_word)" | ||
45 | : $((hopn++)) | ||
46 | elif [ "$hopn" -eq 0 ]; then | ||
47 | echo "Oops, don't know \"$word!\"" >&2 | ||
48 | exit 1 | ||
49 | else | ||
50 | echo "hmm." | ||
51 | : $((hopn--)) | ||
52 | word="${words[-1]}" | ||
53 | fi | ||
54 | done | ||
55 | echo "$word" | ||
56 | } | ||
57 | |||
58 | if [[ "$BASH_SOURCE" = "$0" ]]; then | ||
59 | main "$@" | ||
60 | fi | ||