#!/bin/bash
# Make a temp file
cd /var/www/html/nextcloud_scripts

tmpfile=parsetmp

touch $tmpfile.SUBS
touch $tmpfile.TAX
touch $tmpfile.invoicetotal
touch $tmpfile.invoicenumber

# CSV Column Header
pdftotext -layout $1 $tmpfile 
#cat $tmpfile | tr -d ,\\'"'\' > $tmpfile.new

# Totals
cat $tmpfile | grep "Invoice:" | awk -F : '{print $2}' | tr -d , > $tmpfile.invoicenumber
cat $tmpfile | grep "Sub-Total:\|SubTotal:\|Sub,Total" | awk -F $ '{print $2}' | tr -d , > $tmpfile.SUBS
cat $tmpfile | grep "TAX:\|0: " | awk -F $ '{print $2}' | tr -d , > $tmpfile.TAX
cat $tmpfile | grep "Invoice Total:" | awk -F $ '{print $2}' | tr -d , > $tmpfile.invoicetotal 

#while  read line; do
# echo "$line\n" >> $tmpfile.invoicetotal.new
#done < ${tmpfile}.invoicetotal

totals=$(cat $tmpfile.invoicetotal)

for value in $totals; do
    final=$final"+"${value:1}
done

final=${final:1}
echo $final | bc > $tempfile.total 

echo -e "Invoice Number,Sub Total,TAX,Total,Grand Total" > output.csv
paste -d, $tmpfile.invoicenumber $tmpfile.SUBS $tmpfile.TAX $tmpfile.invoicetotal $tempfile.total >> output.csv

#cleanup time!!!
rm $tmpfile.SUBS -f
rm $tmpfile.invoicenumber -f
rm $tmpfile.TAX -f
rm $tmpfile.invoicetotal -f
rm $tmpfile.new -f
rm $tmpfile -f

ssconvert output.csv output.xls

cat output.xls
