#!/bin/bash

source "${BASH_SOURCE[0]%/*}/.common.sh"


declare -A KNOWN_THEMES=(
	[next]=compile_css.sh
	[next22]=compile.sh
)

_compile_all() (
	echo
	for t in "$@"; do
		echo "Compiling $t ..."
		cd "$VTE_ROOT/themes/$t"
		"${KNOWN_THEMES[$t]}" | prefix_stdout "[$t]" &
	done
	wait
)


compile_themes() {
	if ! available sass; then
		error "Missing compilation tool."
	fi
	
	local themes=()
	if ! (( ${#ARGS[@]} )); then
		themes=( "${!KNOWN_THEMES[@]}" )
		
	else
		for a in "${ARGS[@]}"; do
			if [[ -v KNOWN_THEMES["$a"] ]]; then
				themes+=("$a")
			else
				error "Unknown theme: ${a@Q}"
			fi
		done
	fi
	
	
	_compile_all "${themes[@]}"
	
	if ! ((WATCH)); then
		return;
	fi
	
	
	if ! available inotifywait; then
		error "Cannot watch on your system."
	fi
	
	local mon=(
		--recursive
        --monitor
        --event close_write
        --format '%w%f'
	)
	
	local dirs=()
	for t in "${themes[@]}"; do
		dirs+=("$VTE_ROOT/themes/$t")
	done
	
	local file
	while clear_stdin; read -r file; do
		_compile_all "${themes[@]}"
	done < <(
		inotifywait "${mon[@]}" "${dirs[@]}"
	)
}


# if sourced from another script, run directly
if (return 0 2>/dev/null); then
	[[ -v ARGS ]] || ARGS=()
	[[ -v WATCH ]] || WATCH=
	compile_themes
	return
fi


help() {
	cat <<-EOF
		Usage: ${SELF##*/}  [options..]  [theme..]
		
		Compile scss sources of themes (proxy script).
		
		Options:
		    --help        Show this help
		    --watch       Enable automatic themes compilation on save
		                      (requires inotifywait)
		EOF
}


parse_args() {
	local i=0
	while ((i < ${#ARGS[@]})); do
		local -n arg=ARGS[$i]
		case "$arg" in
			--watch)
				WATCH=1
				;;
			-*)
				help
				exit 1
				;;
			*)
				# theme name
				((i++)) || :
				continue
				;;
		esac
		array_shift ARGS
	done
}


main() {
	parse_args
	compile_themes
}

WATCH=
ARGS=("$@")
main
