#!/bin/sh

#  Copyright (c) 2007 Neil Williams <codehelp@debian.org>
#
#  This program 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.
#
#  This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
#

set -e

# Example script to provide a simple GUI for invoice generation.
# Depends on pilot-qof, datafreedom-perl and zenity.

# This script needs a 'workdir: /path/' setting to be added to
# ~/.datafreedom/currency
# Specify a path to your main pilot-qof data file - the file
# must contain records suitable for --invoice-city, i.e. records
# from pilot_address and pilot_datebook. Records from pilot_expenses
# are handled, if present. pilot_todo records are omitted.

# Currently the script also assumes that your main pilot-qof
# data file is called 'offline.xml' - feel free to tweak this.
# :-)

# If you find this script useful or if you have improvements,
# please let me know so that I can justify making this into a
# part of the main package(s).

ZENITY=0
if [ -e /usr/bin/zenity ]; then
	ZENITY=1
fi
# complain if trying to run via SSH
if [ "$DISPLAY" = "" ] || [ "$SSH_CONNECTION" != "" ]; then
	MSG="zenity cannot run via SSH. aborting..."
	echo $MSG | fold -s
	exit
fi

if [ ! -e /usr/bin/pilot-qof ] || [ $ZENITY = 0 ]; then
	MSG="$0 requires zenity and pilot-qof to be installed. Aborting..."
	echo $MSG | fold -s
	exit
fi

# read the customised data file location
DIR=`cat ~/.datafreedom/currency | grep workdir | gawk -F'workdir:' '{print $2}' | tr -d ' '`
if [ ! -d "$DIR" ]; then
	MSG="Cannot locate data files, value for 'workdir' in ~/.datafreedom/currency"
	MSG="$MSG - $DIR - does not exist."
	echo $MSG | fold -s
	exit
fi
MSG="Select the date of the invoice to view"
DATE=`zenity --calendar --text="$MSG" --date-format="%Y-%m-%d"`
TIME=`date -d"$DATE" +"%A, %B %e %Y"`

if [ ! $DATE ]; then
	echo "$0: please specify the date of the invoice you want to view."
	exit
fi

pilot-qof -x $DIR/offline.xml --invoice-city -t $DATE \
 | dfxml-invoice - > /tmp/zenity
if [ ! -s "/tmp/zenity" ]; then
EMPTY="No invoice data was found for $TIME. Do you want to try another date"
 AGAIN=`zenity --warning --title="No invoice data" --text="$EMPTY"`
 if [ "$AGAIN" = "" ]; then
 `perl $0`
 exit
 fi
fi
zenity --text-info --title="$TIME" --width=500 --height=400 --filename=/tmp/zenity
`perl $0`
