#!/bin/sh
#
# Copyright (C) 2010-2022 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

set -e

if [ $# -ne 4 ] ; then
   echo >&2 "Usage: $0 Template_ODT Output_ODT BibTeX_File Export_Script"
   exit 1
fi

TEMPLATE_ODT="$1"
OUTPUT_ODT="$2"
BIBTEX_FILE="$3"
EXPORT_SCRIPT="$4"
TEMP_ZIP=`mktemp -d`

bibtexconv "$BIBTEX_FILE" <"$EXPORT_SCRIPT" >"$TEMP_ZIP/content.xml"
cp "$TEMPLATE_ODT" "$TEMP_ZIP/template.odt"
( cd "$TEMP_ZIP"
  zip template.odt --out output.odt -x content.xml
  zip output.odt content.xml )
mv "$TEMP_ZIP/output.odt" "$OUTPUT_ODT"

rm -rf "$TEMP_ZIP" || true
