#!/bin/bash

source ./configuration.sh

POVOPT=" -d +q9 +a +W1024 +H768 -v +WT6"
DDIR="frames/visite"
PASS=61
NBFRAMES=2000

STDERR="WS/visite.stderr"
TMPIMG="/dev/shm/tmpvisite.png"
LAST="WS/visite.last"

log_event "start mkvisite $1"

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

for pass in $(seq 0 $PASS)
do

	debut=$(date +"%s")		# start chrono

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

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

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

	if [ $? -ne 0 ]
	then
		convert -blur  9x19 $DDIR/0000.png $outfile
		tail -20 $STDERR
		log_event "FAIL $outfile"
		sleep 100
	else
		txt=$(printf "k:%04d" $idx | tr '01' 'ol')
		tdate=$(date --utc +'%F %H:%M' |  tr '01' 'ol')
		convert ${TMPIMG}			\
			-pointsize 32			\
			-font ${TEXT_TT}		\
			-fill $COLTEXT_A		\
			-annotate +26+46 "${txt}"	\
			-fill $COLTEXT_B		\
			-annotate +29+49 "${txt}"	\
			-font $TEXT_TT			\
			-pointsize 16			\
			-fill  Orange			\
			-gravity South			\
			-annotate +0+8  "$tdate"	\
			$outfile
		echo $txt

		fin=$(date +"%s")
		echo $idx  $((fin-debut)) | tee -a WS/chrono.visite

	fi

	echo $next > $LAST

	sleep   9

done

ffmpeg  -nostdin                                                \
        -loglevel error                                         \
        -y -r 30 -f image2 -i $DDIR/%04d.png			\
	-metadata artist='---[ tTh ]---'			\
	-metadata title='A journey in the wip - 2024'		\
 	-preset veryslow					\
        -c:v libx264 -pix_fmt yuv420p                           \
        visite.mp4

echo "++++++++++++++++"
date --utc +"End $0 at %F %H:%M"
beep -f 1400 -n -r 8
log_event "end mkvisite"
echo
