#!/usr/bin/bash
# morphcv-to-docx.bash
#
# Author: Daniel J. R. May <daniel.may@kada-media.com>
# Version: 0.2, 10 September 2020
# Description: Convert a morphcv XML file to a docx file via RTF.
#
# This file is part of morphcv.
# 
# morphcv 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.
# 
# morphcv 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 morphcv.  If not, see <http://www.gnu.org/licenses/>.

readonly input_path=$1

intermediate_path="$(basename "$input_path" .xml).rtf"
readonly intermediate_path

function print_usage {
    gettext -s 'Usage: morphcv-to-docx FILE'
    gettext -s 'Where FILE is something like: path/to/my-morphcv-file.xml'
}

if [[ -z "$input_path" ]]
then
    gettext -s 'Syntax error: you must specify a morphcv XML file to be converted to docx.'
    print_usage
    exit 1
fi

if [[ ! -e "$input_path" ]]
then
    gettext -s 'File error: the file you specified does not exist, please check your spelling.'
    print_usage
    exit 2
fi

if [[ ! -r "$input_path" ]]
then
    gettext -s 'File error: the file you specified can not be read, please check its file permissions.'
    print_usage
    exit 3
fi

if (! command -v morphcv-to-rtf > /dev/null )
then
    gettext -s 'Requirements error: unable to find the morphcv-to-rtf command which is needed by this program.'
    gettext -s 'morphcv-to-rtf is part of the morphcv package.'
    exit 4
fi

if (! command -v libreoffice > /dev/null )
then
    gettext -s 'Requirements error: unable to find the libreoffice command which is needed by this program.'
    gettext -s 'libreoffice is part of the libreoffice package.'
    exit 5
fi

# We convert the morphcv XML file to RTF and then to docx.
morphcv-to-rtf "$input_path" && \
    libreoffice --convert-to docx "$intermediate_path"
