#!/bin/bash

source ./configuration.sh

POVOPT=" -d +q9 +a +W1024 +H768 -v +WT2"
DDIR="frames/loop"
PASS=55
NBFRAMES=800

STDERR="WS/loop.stderr"
TMPIMG="/dev/shm/tmploop.png"
LAST="WS/loop.last"

if [ ! -r $LAST ] 
then
	echo 200 >  $LAST
fi

log_event "start mkloop"

for pass in $(seq 0 $PASS)
do

	idx=$(cat $LAST)
	next=$(( ( idx + 1 ) % NBFRAMES ))

	outfile=$(printf "%s/%04d.png" $DDIR $idx ) 
	echo $pass "/" $PASS " = " $outfile

	povray -iloop.pov -K${idx} $POVOPT -O${TMPIMG}  2> $STDERR

	if [ $? -ne 0 ]
	then
		tail -14 $STDERR
		log_event "FAIL $outfile"
		sleep 180
	else
		grep 'Trace Time' $STDERR

		txt=$(printf "C:%03d" $idx | tr '01' 'ol')
		tdate=$(date --utc +'%F %H:%M' |  tr '01' 'ol')
		convert ${TMPIMG}			\
			-pointsize 32			\
			-font ${TEXT_TT}		\
			-fill $COLTEXT_A		\
			-annotate +25+60 "${txt}"	\
			-fill $COLTEXT_B		\
			-annotate +28+63 "${txt}"	\
							\
			-pointsize 18			\
			-kerning 0			\
			-fill $COLTIME			\
			-gravity South			\
			-annotate +0+10 "$tdate"	\
			$outfile
		echo $txt
	fi

	echo $next > $LAST

	sleep  233

done

ffmpeg  -nostdin                                                \
        -loglevel error                                         \
        -y -r 30 -f image2 -i $DDIR/%04d.png			\
	-metadata artist='---[ tTh ]---'			\
	-metadata title='* this is just a dirty loop *'		\
 	-preset veryslow					\
        -c:v libx264 -pix_fmt yuv420p                           \
        loop.mp4

echo
date --utc +"End $0 at %F %H:%M"
figlet -W 'hop...' | sed 's/^/    o      /'
beep -f 1119 -n -f 1789 -n -f 1568
log_event "end mkloop"
echo
