#!/bin/bash
# A small handy script to be able to read PDF and DOC files via festival
# In order to properly work this script requires
# working installation of the programs:
# pdftotext, antiword and festival
# This script is licensed under GNU GPL version 2
# Check out the license on http://gnu.org/licenses/gpl2.txt
# Hope that this script will be helpful to Free Software users / community
# Thanks to God (The Holy Trinity) for inspiring me to write that piece of code

trap if_int INT;

# path to pdftotext and festival
pdftotext=$(which pdftotext)
festival=$(which festival);
antiword=$(which antiword);

arg0="$0";
arg1="$1";
arg2="$2";
new_name=$(echo $arg2 |sed -e "s#pdf#txt#gi");
tmp_file="/tmp/$new_name";

 if_int () {
 # bye bye galaxy :]
 rm -f "$tmp_file"
 exit 0;
 }


 help () {
 echo "$arg0 [filetype] [filename]"
 echo "Example $arg0 -t doc examplefilename.doc";

 }

determine_extension () {
pdf_extension="$(file $arg2 |grep pdf|wc -l)";
doc_extension="$(file $arg2 |grep CDF|wc -l)";
if [ "$pdf_extension" == "1" ]; then
extension="pdf";
fi

if [ "$doc_extension" == "1" ]; then
extension="doc";
fi
}


check_and_exec_function () {
if  [ "$arg1" != "-t pdf" ] && [ "$arg1" != "-t PDF" ] && [ "$arg1" != "-tpdf" ] && [ "$arg1" != "-tPDF" ] && [ "$arg1" != "-t doc" ] && [ "$arg1" != "-t DOC" ] && [ "$arg1" != "-tdoc" ] && [ "$arg1" != "-tDOC" ] &&  [ "$extension" != "doc" ] && [ "$extension" != "pdf" ]; then

echo "Wrong [filetype] or [filename] parameter passed in";
exit 1;

fi


if  [ "$arg1" == "-t pdf" ] || [ "$arg1" == "-t PDF" ] || [ "$arg1" == "-tpdf" ] || [ "$arg1" == "-tPDF" ] && [ "$extension" == "pdf" ]; then
pdf_function;

fi

if [ "$arg1" == "-t doc" ] || [ "$arg1" == "-t DOC" ] || [ "$arg1" == "-tdoc" ] || [ "$arg1" == "-tDOC" ] && [ "$extension" == "doc" ]; then
doc_function;

fi

}

pdf_function() { 


if [ "$arg2" != "" ] && [ -f "$arg2" ]; then
if [ "$pdftotext" ]; then
$pdftotext "$arg2" "$tmp_file";
echo "Playing file $arg2";
cat /tmp/$new_name | $festival --tts;
rm -f $tmp_file;
fi
else
echo "Missing [file] argument";
exit 1;
fi


}


doc_function () {


if [ "$arg2" != "" ] && [ -f "$arg2" ]; then
if [ "$antiword" ]; then
echo "Playing file $arg2";
$antiword "$arg2" | $festival --tts;
fi
else
echo "Missing [file] argument";
exit 1;
fi


}
determine_extension;
check_and_exec_function;
