#!/bin/bash

source ./configuration.sh

PASS=87
DELAY=" 159" 
NAME="Thiz iz My Caztel"
NBFRAMES=800

TMPF="/dev/shm/castel.png"
DDIR="frames/castel"
STDERR="WS/castel.stderr"

POVOPT=" -d +q9 +a +W1024 +H768 -v +WT2"

log_event "start castel"

for pass in $(seq 0 $PASS)
do

	idx=$(cat WS/castel.last)
	next=$(( ( idx + 1 ) % NBFRAMES ))
	printf "pass %3d/%3d   next %3d\n" 	\
			$pass $PASS $next
	outfile=$(printf "%s/%04d.png" $DDIR $next)

	povray -icastel.pov -K${next} $POVOPT -O${TMPF} 2> $STDERR

	if [ $? -ne 0 ]
	then
		mogrify -colorspace gray $outfile
		tail -14 $STDERR
		log_event "FAIL $outfile"
		sleep 180
	else
		txt=$(printf "k:%03d" $next | tr '01' 'ol')
		tdate=$(date --utc +'%F %H:%M' |  tr '01' 'ol')
		convert	${TMPF}				\
			-pointsize 36			\
			-kerning  1 			\
			-gravity South-West		\
			-font Courier-Bold		\
			-fill $COLTEXT_A		\
			-annotate +848+42  "$txt"	\
			-annotate +33+42   "$NAME"	\
			-fill  $COLTEXT_B		\
			-annotate +846+40  "$txt"	\
			-annotate +31+40   "$NAME"	\
			-font $TEXT_TT			\
			-pointsize 16			\
			-fill Orange			\
			-gravity South			\
			-annotate +0+9	 "$tdate"	\
			$outfile

		echo $outfile "   " $tdate

	fi

	echo $next > WS/castel.last

	sleep $DELAY

done

ffmpeg  -nostdin                                                \
        -loglevel error                                         \
        -y -r 25 -f image2 -i $DDIR/%04d.png                   \
	-metadata artist='---[ tTh ]---'			\
	-metadata title='* this is just an ugly wip *'		\
        -c:v libx264 -pix_fmt yuv420p                           \
        castel.mp4

echo
figlet -W '* DONE *' | sed 's/^/          /'
beep -f 919 -n -f 1093 -n -f 1568
log_event "end castel"
echo

