#!/bin/sh
# Copyright (C) 2012-2013  Stephan Kreutzer
#
# This file is part of Freie Bibel.
#
# Freie Bibel is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 or any later version,
# as published by the Free Software Foundation.
#
# Freie Bibel 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 3 for more details.
#
# You should have received a copy of the GNU General Public License
# along with Freie Bibel. If not, see <http://www.gnu.org/licenses/>.



if [ $# -ne 2 ]; then
    echo "Usage:\n\thag2epub.sh haggai-xml-file out-directory\n"
    exit 1
fi

if ! test -r "$1"; then
    printf "hag2epub.sh: '$1' isn't readable.\n"
    exit -1;
fi

if ! test -d "$2"; then
    printf "hag2epub.sh: '$2' isn't a directory.\n"
    exit -2
fi

# Escape character \c to avoid trailing \n.
echo "application/epub+zip\c" > "$2/mimetype"

if [ $? != 0 ]; then
    printf "hag2epub.sh: Couldn't write '$2/mimetype'.\n"
    exit -3
fi

if [ ! -d "$2/META-INF" ]; then
    mkdir "$2/META-INF"

    if [ $? != 0 ]; then
        printf "hag2epub.sh: Couldn't create directory '$2/META-INF'.\n"
        exit -4
    fi
fi

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!-- This file was generated by hag2epub.sh (http://www.freie-bibel.de). -->
<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" version=\"1.0\">
  <rootfiles>
    <rootfile full-path=\"main.opf\" media-type=\"application/oebps-package+xml\"/>
  </rootfiles>
</container>" > "$2/META-INF/container.xml"

if [ $? != 0 ]; then
    printf "hag2epub.sh: Couldn't write '$2/META-INF/container.xml'.\n"
    exit -5
fi

xmlstarlet transform hag2opf.xsl $1 > "$2/main.opf"
xmlstarlet transform hag2ncx.xsl $1 > "$2/toc.ncx"
xmlstarlet transform hag2html.xsl $1 > "$2/bible.xhtml"

cd "$2"
# -0 to make 'mimetype' the first file. -X to remove platform-dependend file attributes.
zip -X0 "out.epub" "mimetype"
zip -Xr "out.epub" "META-INF" "main.opf" "toc.ncx" "bible.xhtml"

