aboutsummaryrefslogtreecommitdiff
path: root/bin/rfc
blob: a3f71ef89ab99238ebf721bf80feaa243cc7b8af (plain) (blame)
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/bin/sh
set -eu

D="${XDG_DATA_HOME:-$HOME/.local/share}/doc/rfc"
PROMPT_DB="$(
	cat <<-EOF
		RFC directory does not exist:
		  $D/

		Do you want to download the files to create it?
	EOF
)"

usage() {
	cat <<-'EOF'
		Usage:
		  rfc [-w] RFC_NUMBER
		  rfc -u
		  rfc -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -w            show the path to the RFC file instead of displaying
		                its contents
		  -u            update the local RFC database
		  -h, --help    show this message

		  RFC_NUMBER    the RFC id number


		Lookup the given RFC
		in $XDG_DATA_HOME/doc/rfc/ (defaults to ~/.local/share),
		and feed it into the $PAGER, akin to doing:

		  $ $PAGER $XDG_DATA_HOME/doc/rfc/rfc$RFC_NUMBER.txt

		If the $XDG_DATA_HOME/doc/rfc/ directory doesn't exist, it gets
		created it by downloading the latest RFC files and placing all .txt
		files there.


		Examples:

		  Show RFC 1234 in $PAGER:

		    $ rfc 1234


		  Print path to RFC 2222:

		    $ rfc 2222


		  Download the latest RFCs:

		    $ rfc -u
	EOF
}

view() {
	if [ -t 1 ]; then
		${PAGER:-cat}
	else
		cat
	fi
}

update() {
	rsync -avzP --delete ftp.rfc-editor.org::rfcs-text-only "$D"
	STATUS=$?
	if [ "$STATUS" != 0 ]; then
		exit "$STATUS"
	fi
}

check_local_db() {
	if [ ! -e "$D" ]; then
		if prompt "$PROMPT_DB"; then
			update
		else
			echo 'No local RFC database to operate on.' >&2
			exit 1
		fi
	fi
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'wuh' flag; do
	case "$flag" in
		(w)
			WHERE=true
			;;
		(u)
			UPDATE=true
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

RFC_NUMBER="${1:-}"
F="$D/rfc${RFC_NUMBER}.txt"

check_local_db

if [ "${UPDATE:-}" = true ]; then
	update
	exit
fi

eval "$(assert-arg -- "$RFC_NUMBER" 'RFC_NUMBER')"

if [ ! -e "$F" ]; then
	printf 'Given RFC_NUMBER "%s" does not exist at:\n%s\n' \
		"$RFC_NUMBER" "$F" >&2
	exit 2
fi

if [ "${WHERE:-}" = true ]; then
	printf '%s\n' "$F"
	exit
else
	view < "$F"
	exit
fi