#!/bin/bash

COMMON="$(dirname "$0")"
LISTFILES="$COMMON/listfiles.sh"
READCONF="$COMMON/read_config.sh"

COURSE=$1
[[ $1 == "" ]] && COURSE=$(basename $PWD)

# throw the intermediate results on /dev/shm tmpfs filesystem
URLF=/dev/shm/"$COURSE"_URL_INPUTS

# new method, ripping off the spellcheck algo!
rm -f $URLF
for names in $($LISTFILES) ; do
	grep -H -I \\url{http $names | sed -e 's/:.*\\url{/	/g' -e 's/}.*//'
done | sort -u >$URLF
# check links only once

fix_macro() {
	local URL="$1" MACRO VALUE
	while grep -q '\\' <<<"$URL" ; do
		MACRO=$(sed -re 's/^[^\\]*\\([a-zA-Z_]+).*$/\1/' <<<"$URL")
		if [[ -n $MACRO ]] ; then
			VALUE=$("$READCONF" "$COURSE.tex" "$MACRO")
			#echo "MACRO: $MACRO=$VALUE" >&2
			URL=$(sed -re "s/\\\\$MACRO/$VALUE/" <<<"$URL")
		else
			break
		fi
	done
	echo "$URL"
}

# Changed from curl to wget, because curl didn't properly follow 302 redirects
getURL() {
	wget --server-response --spider "$@" 2>&1 | awk '/HTTP\// {RC=$2}; END{print RC}'
}

getRC() {
	local URL=$1 RC
	if [[ $URL =~ ://localhost ]] ; then
		echo "200"
		return
	fi
	[[ -n $PROGRESS ]] || echo -n '.' >&2
	RC=$(getURL "$URL")
	if [[ $RC -eq 401 ]] ; then
		# Try the password since might be CM site
		RC=$(getURL --user=LFtraining --password=Penguin2014 "$URL")
	elif [[ $RC -eq 403 || $RC = UNKNOWN ]] ; then
		# Problematic URL: Just try to get the web page
		RC=$(wget -O /dev/null "$URL" 2>&1 | awk '/^HTTP/ {print $6}')
	fi
	echo "$RC"
}

readRC() {
	local RC=$1 FILE=$2
	case "$RC" in 
		200) [[ -n $QUIET ]] || \
		     echo "GOT $RC: Good Link at:      $URL";;
		301) echo "GOT $RC: Moved Permanently: $URL ($FILE)";;
		301) [[ -n $QUIET ]] || \
		     echo "GOT $RC: Moved Temporarily: $URL (essentially 200)";;
		401) echo "GOT $RC: Unauthorized:      $URL ($FILE)";;
		403) echo "GOT $RC: Forbidden Access:  $URL ($FILE)";;
		404) echo "GOT $RC: Not Found:         $URL ($FILE)";;
		*)   echo "GOT $RC: UNKNOWN :-( HELP!  $URL ($FILE)";;
	esac
}

cat $URLF | while IFS='	' read -r FILE URL ; do
	URL=$(fix_macro "$URL")
	RC=$(getRC "$URL")
	readRC "$RC" "$FILE"
done
echo
