#!/bin/bash
# docx.sh
# Description: Helper for ne macro to convert from markdown to docx
#
# Copyright 2019, F123 Consulting, <information@f123.org>
# Copyright 2019, Storm Dragon, <storm_dragon@linux-a11y.org>
#
# This 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, or (at your option) any later
# version.
#
# This software 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 package; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#--code--
 
declare -A message=(
    # Change the strings in quotes for different languages.
    [confirm]="The file is available as"
    [continue]="Press enter to continue."
    [error]="The file was not converted."
    [prompt]="Enter file name: "
)

# Get the file name for the conversion.
read -erp "${message[prompt]}" fileName

# If variable is empty, do not write a file.
if [[ -z "$fileName" ]]; then
    read -p "$message[error] ${message[continue]}" continue
    exit 0
fi

# make sure fileName is in proper format.
fileName="$HOME/Documents/${fileName##*/}"

# Find out what we are converting to.
convertTo="${0##*/}"
convertTo="${convertTo%%.*}"

# Add the proper extension if needed.
extension="${fileName,,}"
extension="${extension##*.}"

if [[ "$extension" != "$convertTo" ]]; then
    fileName+=".$convertTo"
fi

# Make sure we don't overwrite anything.
i=2
oldFileName="$fileName"
while [[ -f "$fileName" ]]; do
    fileName="${oldFileName}"
    fileName="${fileName%.*}"
    fileName="${fileName%-[0-9]*}"
    fileName="${fileName}-${i}.${convertTo}"
    ((i++))
done

# Convert the file to html
if ! markdown -o ~/.ne/.tmp.txt.html ~/.ne/.tmp.txt ; then
    read -p "${message[error]} ${message[continue]}" continue
    exit 1
fi

# Convert the file to the specified extension.
if lowriter --headless --convert-to $convertTo ~/.ne/.tmp.txt.html --outdir ~/.ne &> /dev/null ]]; then
    mv ~/.ne/.tmp.txt.$convertTo "$fileName"
    read -p "${message[confirm]} $fileName. ${message[continue]}" continue
else
    read -p "${message[error]} ${message[continue]}" continue
fi

