#!/bin/bash
echo "Convert scad to gif"
pwd
#
# to do if file = *.scad 
# file = "${file::-5}"
# 

fnum=1000;
x=1;
y=0;
z=0;
string=$1;
file=${string%.*};		# skip extension
maxproc=5;
create_png() {
#echo "Create $fnum x:$x y:$y z:$z "
if [  $(pgrep -c openscad) -ge $maxproc ]
then 
	echo "Even wachten"
	openscad -q -D 'run="all"' $file.scad  --viewall --camera=0,0,0,$x,$y,$z,30 -o "tmp$fnum.png" 
else 
#	echo "En door"
	openscad -q -D 'run="all"' $file.scad  --viewall --camera=0,0,0,$x,$y,$z,30 -o "tmp$fnum.png" &
	sleep 0.01
fi 

}
# create stl files
echo "Create stl files"

grep module $file.scad | awk '{print $2}' | awk -F '(' '{print $1}' | while read -r line ; do

if [[  "$line" ==  "print_"* ]] || [ "$line" == "all" ]; then
	openscad -q -D 'run="'$line'"' $file.scad  -o "$line.png" &
fi
if [[  "$line" ==  "print_"* ]]; then
echo "$file:$line";
	openscad -q -D 'run="'$line'"' $file.scad  -o "$line.stl"
fi
done
echo "Done STL print_module files";

# create gif file

for x in {0..180..1} 
do 
	((fnum=fnum+1))
	create_png
done
x=180;
for y in {0..360..1} 
do 
	((fnum=fnum+1))
	create_png
done
y=0;
for x in {181..360..1} 
do 
	((fnum=fnum+1))
	create_png
done
until [ -f tmp$fnum.png ]
do 
	sleep 1
done
sleep 5
date
echo "Start converting to gif"
# convert -delay 10 -loop 0 *.png $file.gif
#gifski -o $file.gif *.png
rm -f $file.mp4
ffmpeg -framerate 30 -pattern_type glob -i 'tmp*.png' -c:v libx264 -pix_fmt yuv420p $file.mp4
date
echo "Start cleaning up"
#rm p{1001..$fnum}.png
rm tmp*.png
echo "Done"

