#!/bin/bash

#take specific directory/ies as arguments
dirs=("$@")

#if you don't give this command a list of directories to use, it will recursively search the current directory for the Document.xml project file, and use the parent directories of these to package .FCStd files
if [ "${dirs}x" == "x" ]	
then
	dirs=$(find . -iname "Document.xml" -printf "'%p'\n" | xargs dirname | sort -u)
fi
prev_dir=$(pwd)
echo "${dirs}" | while read -r d
do
	cd "${d}"
	fname=$(basename "${d}")
	#freecad requires a specific structure to the zipped file, wherein the Document.xml file is first, then every file name that is parsed in the Document.xml file needs to come in that order; this ordering is not apparent when viewing the .zip archive with e.g. 7zip.  
	#there should not be a reason this is necessary, but it is, so we must depend on the user to have freecad installed for this script
	freecad -c "from freecad import project_utility; project_utility.createDocument(\"$(pwd)/Document.xml\", \"../${fname}.FCStd\")"
	#if freecad had a more normal structure for reading its own files, a simple zip command like below could be used
	#zip -9 -q -r ../"${fname}".FCStd *
	cd "${prev_dir}"
done
