#!/bin/sh

: ${CC:=gcc}
: ${CARGS:=-std=c99 -lm -O3}
: ${FPS:=30}
: ${PLAYER:=mpv}
: ${PLAYERARGS:=--no-correct-pts --container-fps-override=\$FPS -}
: ${RENDER:=ffmpeg}
: ${RENDERARGS:=-r \$FPS -i - \$bin.mp4}

binname() {
	name="${1%%.c}"
	echo "${name##*/}"
}

make_compile() {
	bin="$(binname "$1")"
	$(eval "echo \"$CC\"") $(eval "echo \"$CARGS\"") AnimationRender/*.c FrameRender/*.c RGBImage/*.c "$1" -o "$bin"
}

make_run() {
	bin="$(binname "$1")"
	"./$bin" | $(eval "echo \"$PLAYER\"") $(eval "echo \"$PLAYERARGS\"")
}

make_render() {
	bin="$(binname "$1")"
	"./$bin" | $(eval "echo \"$RENDER\"") $(eval "echo \"$RENDERARGS\"")
}

if [ ! -f "$2" ]
then
	echo "'$2' is not valid! Must be the path to a C file which contains main function."
	exit 2
fi

case "$1" in
	(compile)
		make_compile "$2"
		;;
	(run)
		make_compile "$2"
		make_run "$2"
		;;
	(render)
		make_compile "$2"
		make_render "$2"
		;;
	(*)
		echo "Unrecognised action '$1'!"
		exit 1
esac
