#!/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
