#!/usr/bin/env sh

#$(export DIM=64; export FILE=filter; mkdir "${DIM}x${DIM}"; inkscape -w ${DIM} -h ${DIM} svg/${FILE}.svg -o "${DIM}x${DIM}/${FILE}.png")

DIMENSIONS=""
DIMENSIONS="${DIMENSIONS} 16"
DIMENSIONS="${DIMENSIONS} 24"
DIMENSIONS="${DIMENSIONS} 32"
DIMENSIONS="${DIMENSIONS} 48"
DIMENSIONS="${DIMENSIONS} 64"
#DIMENSIONS="${DIMENSIONS} 128"
#DIMENSIONS="${DIMENSIONS} 256"

# Targer directories.
THEME_DARK="dark"
THEME_LIGHT="light"
THEME_DISABLED="disabled"

# Itermediate SVG source directories.
SVG_DIR_DARK="svg_dark"
SVG_DIR_LIGHT="svg_light"
SVG_DIR_DISABLED="svg_disabled"
SVG_DIR_PERMANENT="svg_permanent"

# Controls preformed actions.
GENERATE_DARK="yes"
GENERATE_LIGHT="yes"
GENERATE_DISABLED="yes"
GENERATE_PERMANENT="yes"

generate_pngs () {
	local SRC_DIR="$1"
	local THEME_BASE_DIR="$2"

	if [ "x${SRC_DIR}" = "x" ]; then
		echo "Missing source directory name as parameter." >&2
		return 1
	fi

	if [ "x${THEME_BASE_DIR}" = "x" ]; then
		echo "Target directory as parameter." >&2
		return 1
	fi

	if [ ! -d ${SRC_DIR} ]; then
		echo "Directory ${SRC_DIR} doesn't exist or isn't a directory." >&2
		return 1
	fi

	for SVG_PATH in ${SRC_DIR}/*; do

		local SVG_FILE=$(echo ${SVG_PATH} | sed -e 's/^.*\///g') # Strip leading path up to last '/'.
		local PNG_FILE=$(echo ${SVG_FILE} | sed -e 's/\..*$/.png/g') # Replace complete suffix with ".png".

		for DIM in ${DIMENSIONS}; do
			local TGT_DIR="${THEME_BASE_DIR}/${DIM}x${DIM}"
			local PNG_PATH="${TGT_DIR}/${PNG_FILE}"
			# Create missing directory.
			if [ ! -e ${TGT_DIR} ]; then
				mkdir -p ${TGT_DIR}
			fi
			# Test directory existence.
			if [ ! -d ${TGT_DIR} ]; then
				echo "Directory ${TGT_DIR} doesn't exist or isn't a directory." >&2
				return 1
			fi
			# Convert images.
			if inkscape -w ${DIM} -h ${DIM} ${SVG_PATH} -o "${PNG_PATH}"; then
				echo "Succeeded: ${SVG_PATH} -> ${PNG_PATH}"
			else
				echo "Failed: ${SVG_PATH} -> ${PNG_PATH}" >&2
			fi
		done
	done

	return 0
}


if [ "x${GENERATE_DARK}" = "xyes" ]; then

	generate_pngs "${SVG_DIR_DARK}" "${THEME_DARK}" || exit 1

fi


if [ "x${GENERATE_LIGHT}" = "xyes" ]; then

	generate_pngs "${SVG_DIR_LIGHT}" "${THEME_LIGHT}" || exit 1

fi


if [ "x${GENERATE_DISABLED}" = "xyes" ]; then

	generate_pngs "${SVG_DIR_DISABLED}" "${THEME_DISABLED}" || exit 1

fi


if [ "x${GENERATE_PERMANENT}" = "xyes" ]; then

	generate_pngs "${SVG_DIR_PERMANENT}" "${THEME_DARK}" || exit 1
	generate_pngs "${SVG_DIR_PERMANENT}" "${THEME_LIGHT}" || exit 1

fi
