#!/usr/bin/env sh

set -e
#set -x

ARGUMENTS="$@"

TEMP=$(getopt -o 'a:b:d:hso:nv' -l 'attribute:,backend:,doctype:,help,no-header-footer,out-file:,section-numbers,safe,theme:,verbose,version' -n asciidoc -- "$@")

if [ $? -ne 0 ]; then
	exit 1
fi

eval set -- "$TEMP"
unset TEMP

NO_HEADER_FOOTER=
OUT_DIR=
OUT_FILE=
SAFE=0
VERBOSE=0

while true; do
	case "$1" in
		'-a'|'--attribute')
			echo 'The option -a|--attribute is currently ignored.' >&2
			shift 2 ;;
		'-b'|'--backend')
			echo 'The option -b|--backend is currently ignored.' >&2
			shift 2 ;;
		'-d'|'--doctype')
			echo 'The option -d|--doctype is currently ignored.' >&2
			shift 2 ;;
		'-h'|'--help')
			echo 'TODO'
			exit 0 ;;
		'-s'|'--no-header-footer')
			NO_HEADER_FOOTER=1
			shift ;;
		'-o'|'--out-file')
			OUT_DIR=`dirname $2`
			OUT_FILE=`basename ${2%.*}`
			shift 2 ;;
		'-n'|'--section-numbers')
			echo 'The option -n|--section-numbers is currently ignored.' >&2
			shift ;;
		'--safe')
			SAFE=1
			shift ;;
		'--theme')
			echo 'The option --theme is currently ignored.' >&2
			shift ;;
		'-v'|'--verbose')
			VERBOSE=1
			shift ;;
		'--version')
			echo 'Asciideck compatibility script'
			exit 0 ;;
		'--')
			shift
			break ;;
		*)
			echo 'Unexpected error:' $1 >&2
			exit 1 ;;
	esac
done

IN_FILE=

case "$1" in
	'')
		echo 'No file name was provided. Use - for standard input.' >&2
		exit 1 ;;
	'-')
		PARSE_CALL="asciideck:parse_stdin()" ;;
	*)
		IN_FILE=$1
		PARSE_CALL="asciideck:parse_file(\"$IN_FILE\")" ;;
esac

if [ $IN_FILE -a -z $OUT_FILE ]; then
	OUT_DIR=`dirname $IN_FILE`
	OUT_FILE=`basename ${IN_FILE%.*}`
fi

# We need a dummy variable to not have to worry about commas
# so let's pass the original command line forward.
TRANSLATE_OPTS="#{ command_line => \"$0 $ARGUMENTS\""
if [ $OUT_FILE ]; then
	TRANSLATE_OPTS="$TRANSLATE_OPTS, outdir => \"$OUT_DIR\", outfile => \"$OUT_FILE\""
fi
if [ $NO_HEADER_FOOTER ]; then
	TRANSLATE_OPTS="$TRANSLATE_OPTS, no_header_footer => true"
fi
TRANSLATE_OPTS="$TRANSLATE_OPTS }"

<&0 erl +A0 -boot no_dot_erlang -noshell -pz `dirname $0`/../ebin -eval " \
	case asciideck:to_html($PARSE_CALL, $TRANSLATE_OPTS) of \
		ok -> ok; \
		Output -> io:format(\"~ts~n\", [Output]) \
	end, \
	halt()"
