aboutsummaryrefslogtreecommitdiff
path: root/bin/rfc
blob: a4835958b288ff3008b41b922e1ecad4e2734d6a (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
#!/bin/sh
set -eu

TARBALL_URL='https://www.rfc-editor.org/in-notes/tar/RFC-all.tar.gz'

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

help() {
	cat <<-'EOF'

		Options:
		  -w            Show the path to the RFC file instead of displaying
		                its contents.
		  -h, --help    show this message

		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 tries to
		create it by downloading the latest RFC tarball [0] and placing all .txt
		files there.
	EOF

	printf '\n[0]: %s\n' "$TARBALL_URL"
}

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

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

RFC_NUMBER="${1:-}"
if [ -z "$RFC_NUMBER" ]; then
	echo 'Missing argument RFC_NUMBER' >&2
	usage >&2
	exit 2
fi

D="${XDG_DATA_HOME:-$HOME/.local/share}/doc/rfc"
if [ ! -e "$D" ]; then
	printf 'RFC directory does not exist:\n\t%s/\n\n' "$D"
	printf 'Do you want to download the files to create it? [Y/n] '
	read -r yesno
	if [ "$yesno" != 'n' ] && [ "$yesno" != 'N' ]; then
		CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/rfc-cli"
		mkdir -p "$CACHE_DIR"
		wget -cO "$CACHE_DIR"/RFC-all.tar.gz "$TARBALL_URL"
		rm -rf "$CACHE_DIR/tmp"
		mkdir -p "$CACHE_DIR/tmp"
		tar \
			-C "$CACHE_DIR/tmp"              \
			-xvf "$CACHE_DIR"/RFC-all.tar.gz \
			--wildcards                      \
			'rfc*.txt'
		mkdir -p "$(dirname "$D")"
		mv "$CACHE_DIR/tmp" "$D"
	fi
fi

F="$D/rfc${RFC_NUMBER}.txt"
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
fi

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

view < "$F"