#!/bin/sh
#
# /usr/local/bin/localikiwatchstyling
# Copyright 2014 Jonas Smedegaard <dr@jones.dk>
#
# Watch Ikiwiki styling and regenerate with debug hints when it changes
#
# Depends: ruby-compass, entr
# Recommends: libnotify-bin

showhelp() {
	cat <<EOF
Usage:   $PRG [-v|--verbose]

Execute at the root of an Ikiwiki project to watch styling folder
and regenerate with debug hints applied when main SCSS file changes.
EOF
}

exit1()	{
	echo >&2 "Error: $1"
	echo >&2 "Exiting..."
	exit 1
}

PRG=$(basename "$0")

TEMP=$(getopt -s sh -o hv -l help,verbose -n "$PRG" -- "$@")
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$TEMP"

verbose=
while true ; do
	case "$1" in
		-h|--help) showhelp; exit 0 ;;
		-v|--verbose) verbose=x; shift ;;
		--) shift ; break ;;
		*) echo >&2 "ERROR: Internal error resolving options." ; exit 1 ;;
	esac
done

stem=
if [ -f styling/style.scss ]; then
	stem=style
elif [ -f styling/local.scss ]; then
	stem=local
else
	exit1 "Failed to locate style.scss or local.scss in styling dir."
fi

echo styling/$stem.scss \
	| entr sh -c "\
		set -eu$verbose;\
		cd styling;\
		{\
			cat $stem.scss;\
			if grep -Fxq '@import \"compass/typography/vertical_rhythm\";' $stem.scss; then \
				echo 'body {@include debug-vertical-alignment;}';\
			fi;\
		} | scss -s --compass -g $stem.css;\
		cp $stem.css ../build/html/$stem.css;\
		if [ -n "$DISPLAY" ] && [ -e /usr/bin/notify-send ]; then \
			notify-send \
				'Ikiwiki watch' \
				'CSS refreshed from styling/$stem.scss';\
		fi"