#!/bin/bash
# List all tex files for a course
# Written by: Behan Webster
#################################
set -e

VERSION=1.7

#################################
colors() {
	RED="\e[0;31m"
	#GREEN="\e[0;32m"
	#YELLOW="\e[0;33m"
	CYAN="\e[0;36m"
	BLUE="\e[0;34m"
	BACK="\e[0m"
}

#################################
debug() {
	[[ -z $DEBUG ]] || echo -e "${BLUE}D: $*${BACK}" >&2
}
error() {
	echo -e "${RED}E: $*${BACK}" >&2
	exit 1
}
info() {
	[[ -n $QUIET ]] || echo -e "${CYAN}I: $*${BACK}" >&2
}
verbose() {
	[[ -z $VERBOSE ]] || echo "+ $*" >&2
	# shellcheck disable=SC2048
	[[ -n $TEST ]] || $*
}

#################################
get_tex_dirs() {
	local FILE=$1
	( grep -vE '^%' "$FILE" | grep 'subimport' || true ) \
		| sed -re 's|^.*\{(.*)\/}\{index\}.*$|\1|;'
	( grep -vE '^%' "$FILE" | grep 'input' || true ) \
		| sed -re 's|\\input\{(.*)\}$|\1.tex|;' -e 's/\.tex\.tex$/.tex/;'
}
 
#################################
FILEEXTS="tex inc"
find_tex_files() {
	local DIR EXT
	for DIR in "$@" ; do
		for EXT in $FILEEXTS ; do
			debug "Look for *.$EXT in $DIR"
			# Dereference all symlinks with realpath,
			# or we'll destroy symlinks
			find "$DIR" -maxdepth 4 -name "*.$EXT" -print0 \
				| xargs -0 --no-run-if-empty realpath \
				| sort
		done
	done
}

######################################################################
# Read singular config from course tex file
read_tex() {
        local FILE=$1
        local KEY=$2

        # shellcheck disable=SC1003
        grep -E '\\newcommand{\\'"$KEY"'}' "$FILE" | head -1 \
                | sed -re 's/.*\{(.*)\}$/\1/; s/\\_/_/g'
}

#################################
list_texfiles() {
	local FILE=$1
	debug "list_tex_files: $FILE"
	local DIRS ARCH BOARD

	ARCH="$(read_tex "$FILE" arch)"
	BOARD="$(read_tex "$FILE" board)"
	DIRS="$(pwd) "$(get_tex_dirs "$FILE" \
		| sed -r -e 's/\\arch/'$ARCH'/g' -e 's/\\board/'$BOARD'/g')
	# shellcheck disable=SC2086
        debug "list_textfiles:" $DIRS
	# shellcheck disable=SC2086
	find_tex_files $DIRS
	# shellcheck disable=SC2086
}

#################################
usage() {
	local CMD
	CMD=$(basename "$0")
	echo "Usage: $CMD <options> [course.tex]"
	echo "    -e --extention EXT  Look for *.EXT in each directory"
	echo "    -h --help           Print this help"
	echo "    -q --quiet          No output (except for running aspell)"
	echo "    -v --verbose        Show all the commands executed"
	echo "    -V --version        Print out the version of this script"
	exit 0
}
 
#################################
version() {
	local CMD
	CMD=$(basename "$0")
	echo "$CMD v$VERSION"
	exit 0
}
 
#################################
while [[ $# -gt 0 ]] ; do
	case $1 in
		-c|--color) colors ;;
		--debug) DEBUG=y ;;
		--Debug) colors; DEBUG=y; VERBOSE=y ;;
		-e|--extension) FILEEXTS+=" $2"; shift ;;
		-q|--quiet) QUIET=y ;;
		--test) TEST=y; VERBOSE=y ;;
		--trace) set -x ;;
		-v|--verbose) VERBOSE=y ;;
		-V|--version) version ;;
		-h|--help) usage ;;
		--|*) break ;;
	esac
	shift
done

#################################
# Find course.tex file
FILE="$*"
if [[ -z $FILES ]] ; then
	if [[ -f "index.tex" ]] ; then
		FILE="index.tex"
	else
		COURSE=${COURSE:-$(basename "$PWD")}
		FILE="${1:-$COURSE.tex}"
		if [[ ! -f $FILE ]] ; then
			error "File not found: $FILE"
		fi
	fi

	#################################
	# Handle course.tex in another directory
	DIR=$(dirname "$FILE")
	FILE=$(basename "$FILE")
	cd "$DIR"
fi

#################################
# Read config file
CONFIG=.listfilesrc
if [[ -e $CONFIG ]] ; then
	info "Reading local config file: ${DIR:+$DIR/}$CONFIG"
	if [[ -n $DEBUG ]] ; then
		debug "Contents of config file"
		cat $CONFIG
	fi
	source $CONFIG
fi

#################################
list_texfiles "$FILE" | ${PAGER:-less}
