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

SLICER_CONFIG=bakje.ini
SCAD_FILE=bakje.scad

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

mkdir -p stl gcode
rm stl/*
rm -r gcode/*

nl="
"

for part in bakje grid ;
do
	for x in {1..4}
	do
		for y in {1..4}
		do
			${OPENSCAD} -o stl/"${part}-${x}x${y}.stl" \
				-D "RENDER=\"${part}\"" \
				-D WIDTH=${x} \
				-D DEPTH=${y} \
				"${SCAD_FILE}" || exit 1

			fitX=$(expr 4 / $x)
			fitY=$(expr 4 / $y)
			# echo "size = $x x $y"
			# echo "fit = $fitX x $fitY"

			dubs="1\n2\n4\n6\n9"

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

			echo "${x}x${y}: ${max}x${min}"

			if [ "$max" == "$min" ]
			then
				if [ "${x}" == "1" ]
				then
					dubs=(1 2 4 9 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 4 5)
				elif [ "${max}" == "4" ]
				then
					dubs=(1 2 4)
				fi
			elif [ "${min}" == "2" ]
			then
				dubs=(1 2)
			else
				dubs=(1)
			fi

			echo "${x}x${y}: ${dubs[*]}"



			for dub in ${dubs[*]}
			do
				slice ${part} ${x}x${y} ${dub}
			done

			# for X in $(seq 1 $fitX)
			# do
			# 	for Y in $(seq 1 $fitY)
			# 	do
			# 		count=$(expr $X \* $Y)
			# 		if [ $(expr $X - $Y) -lt 2 ] && [ $(expr $Y - $X) -lt 2 ]
			# 		then
			# 			slice ${part} ${x}x${y} ${count}
			# 		fi
			# 		echo -n
			# 	done
			# done
		done
	done
done

