#!/bin/sh
# Create a distributable archive for my lesson material
ARCHIVE="$(basename "$PWD").zip"
zip "${ARCHIVE}" $(find . -mindepth 1 -not -path './.*' -printf '%p ')

# TODO: replace hardcoded base dir
BASEDIR=/home/muhq/Documents/MyDocuments/Work/Schule/Unterricht

add_to_archive() {
python3 <<EOF 
import zipfile
with zipfile.ZipFile("${ARCHIVE}", "a") as zf:
    zf.write("$1", "$2")
EOF
}

add_custom_latex_to_archive() {
	for path in "$@"
	do
	    path_in_arc="$(echo "${path}" | sed -e "s%${BASEDIR}/%%")"
	    add_to_archive "${path}" "${path_in_arc}"
	done
}

# Include license
add_custom_latex_to_archive "${BASEDIR}"/COPYING

# Include common latex code
add_custom_latex_to_archive "${BASEDIR}"/latex/common.tex \
	"${BASEDIR}"/latex/common_packages.tex \
	"${BASEDIR}"/latex/common_options.tex

# Include common images
add_custom_latex_to_archive "${BASEDIR}"/latex/images/**

# Include the needed latex classes
if grep -Pzrq '(?s)documentclass.+test\}' .; then
    add_custom_latex_to_archive "${BASEDIR}"/latex/test.cls
fi

if grep -Pzrq '(?s)documentclass.+arbeitsauftrag\}' .; then
    add_custom_latex_to_archive "${BASEDIR}"/latex/arbeitsauftrag.cls
fi

if grep -Pzrq '(?s)documentclass.+handout\}' .; then
    add_custom_latex_to_archive "${BASEDIR}"/latex/handout.cls
fi

include_planning=
if grep -Pzrq '(?s)documentclass.+map\}' .; then
    add_custom_latex_to_archive "${BASEDIR}"/latex/map.cls
    include_planning=true
fi

if grep -Pzrq '(?s)documentclass.+sequence\}' .; then
    add_custom_latex_to_archive "${BASEDIR}"/latex/sequence.cls
    include_planning=true
fi

if [ -n "${include_planning}" ]; then
    add_custom_latex_to_archive "${BASEDIR}"/latex/common_planning*.tex
fi

