#!/bin/bash

source ./configuration.sh

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

STDERR="WS/formes.stderr"
TMPIMG="/dev/shm/tmpformes.png"
LAST="WS/formes.last"

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

log_event "start mkformes"

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 -iformes.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')

		echo "space date" $tdate
		convert ${TMPIMG}			\
			-pointsize 40			\
			-font ${TEXT_TT}		\
			-fill $COLTEXT_A		\
			-annotate +25+60 "${txt}"	\
			-fill $COLTEXT_B		\
			-annotate +28+57 "${txt}"	\
							\
			-pointsize 16			\
			-kerning 0			\
			-fill $COLTIME			\
			-gravity South			\
			-annotate +0+10 "$tdate"	\
			$outfile
		echo $txt
	fi

	echo $next > $LAST

	sleep  70

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                           \
        formes.mp4

echo
date --utc +"End $0 at %F %H:%M"
figlet -W 'hop...' | sed 's/^/    o      /'
beep -f 1100 -n -f 1200 -n -f 1400
log_event "end mkformes"
echo
