#!/bin/bash

usage="A quick hack to fix an issue with incomplete UTF-8 support in
ebook2cw.  Reads the FIRST argument as the filename to convert, passes
the rest to ebook2cw as options.  Reads ~/.ebook2cw/ebk2cw.txt for
conversions.

Any line of ebk2cw.txt with no \"=\" on it will be ignored; use this
for inelegant comments.  Substitutions are in the form: \"a=b\".  Due
to an untraced bug, it appears there cannot be a substitution on the
first line of ebk2cw.txt.  The substitutions can be anything supported
by sed, although no provision is made for using \"=\" in either
pattern or replacement.  Use ebook2cw's utf8map.txt for that.

Version 0.2: Added pattern debugging, in a somewhat hackish way.  If the variable DEBUG is non-null, ebk2cw will instead output the sed command to run, and write the converted file that would be given to ebook2cw to ./ebk2cwdebug.txt

Version 0.2, November 26, 2014.  Released under GNU GPL version 2 or
later.  Written by Tor Chantara, NH7XC <marqueteur@fineartmarquetry.com>"

# History:
# Version 0.1 November 26, 2014   First working version.
# Version 0.2 November 20, 2016   Added pattern debugging

DEBUG= #set to anything to turn on
debecho () {
  if [ ! -z "$DEBUG" ]; then
     echo "$1" >&2
  fi
}

if ! which ebook2cw > /dev/null
then
    echo "Cannot find ebook2cw.  Exiting"
    echo
    echo "$usage"
    exit 1
fi

if [[ ! -e ~/.ebook2cw/ebk2cw.txt ]]
then
    echo "No substitution list found.  Put one at ~/.ebook2cw/ebk2cw.txt with lines of the form \"a=b\""
    echo
    echo "$usage"
fi

if [[ -z $1 ]]
then
    echo "Must have file to convert. Exiting"
    echo
    echo "$usage"
    exit 1
elif [[ ! -f $1 ]]
then
    echo "$1 is not a file.  Exiting"
    echo
    echo "$usage"
    exit 1
else
    ebk=$1
    shift
fi


substitutions=''
substitutionslist="`cat ~/.ebook2cw/ebk2cw.txt`"

for line in $substitutionslist
do
    if echo "$line" | grep "=" > /dev/null
    then
	substitutions="$substitutions -e s/"`echo -n "$line"|cut -sf1 -d"=" -`"/"`echo -n "$line"|cut -sf2 -d"="`"/g"
	# The above is a monster, but it works.  I'm not sure the -s
	# (skip no delim lines) is needed, but I don't have time to
	# fix now.
    fi
done


if [ -z "$DEBUG" ]; then
    cat "$ebk"|sed $substitutions|ebook2cw "$@" -
else
    echo "sed $substitutions"
    cat "$ebk"|sed $substitutions>./ebk2cwdebug.txt
fi


exit 0

