
OPENSCAD=openscad
PRUSASLICER="flatpak run com.prusa3d.PrusaSlicer"

SLICER_CONFIG=bakje.ini
SCAD_FILE=bakje.scad

nl="
"

function slice(){
	part=$1
	size=$2
	count=$3
	fileName="${part}/${size}/${count}-{print_time}.gcode"
	mkdir -p "${part}/${size}"
	${PRUSASLICER} \
		--slice \
		--load \"$SLICER_CONFIG\" \
		--duplicate ${count} \
		--output "${fileName}" \
		stl/${part}-${x}x${y}.stl || exit 1
	sleep 0.5
}

function renderBakjes(){
	for part in bakje grid ;
	do
		for x in {1..4}
		do
			for y in {1..4}
			do
				echo "$0: render $part ${x}x${y}"
				${OPENSCAD} -o stl/"${part}-${x}x${y}.stl" \
					-D "RENDER=\"${part}\"" \
					-D WIDTH=${x} \
					-D DEPTH=${y} \
					"${SCAD_FILE}" || exit 1

				max=$(echo "$x$nl$y" | sort --numeric-sort --reverse | head --lines 1)
				min=$(echo "$x$nl$y" | sort --numeric-sort | head --lines 1)

				if [ "$max" == "$min" ]
				then
					if [ "${x}" == "1" ]
					then
						dubs=(1 2 4 6 9 12 16)
					elif [ "${x}" == "2" ]
					then
						dubs=(1 2 4)
					else
						dubs=(1)
					fi
				elif [ "${min}" == "1" ]
				then
					if [ "${max}" == "2" ]
					then
						dubs=(1 2 4 6 8)
					elif [ "${max}" == "3" ]
					then
						dubs=(1 2 3 4)
					elif [ "${max}" == "4" ]
					then
						dubs=(1 2 4)
					fi
				elif [ "${min}" == "2" ]
				then
					dubs=(1 2)
				else
					dubs=(1)
				fi

				for dub in ${dubs[*]}
				do
					echo "$0: slice $dub dublicates of $part ${x}x${y}"
					slice ${part} ${x}x${y} ${dub}
				done
			done
		done
	done
}

mkdir -p stl bakje grid koffer
rm stl/*
rm -r bakje/* grid/*

renderBakjes
