#!/bin/bash

# usage statement
if [ $# != 3 ]; then
	echo -e "usage: $0 renter_name date amount_paid\nexample: Duane_Odom 09-25-2007 550"
	exit 1
fi

# variable assignment
RENTER_NAME=$1
#RECIEPT_DATE=`date +%m-%d-%Y`
RECEIPT_DATE=$2
AMOUNT_PAID=$3
ADDRESS_FILE="$RENTER_NAME/address"
RENT_AMOUNT_FILE="$RENTER_NAME/rent_amount"
RENT_RECEIPT_FILE="$RENTER_NAME/$RECEIPT_DATE.html"


# if the renter's directory exists
if [ -d "$RENTER_NAME" ]; then
	# if the renter's address exists
	if [ -f "$ADDRESS_FILE" ]; then
		ADDRESS=`cat $ADDRESS_FILE`
	else
		echo "No address file exists for the renter $RENTER_NAME!"
		exit 1
	fi

	# if the renter's rent amount exists
	if [ -f "$RENT_AMOUNT_FILE" ]; then
		AMOUNT_DUE=`cat $RENT_AMOUNT_FILE`
		AMOUNT_PAST_DUE=`echo "$AMOUNT_DUE - $AMOUNT_PAID" | bc -l`
	else
		echo "No rent_amount file exists for the renter $RENTER_NAME!"
		exit 1
	fi

	# perform the variable substitution
	cat Default_Receipt.html | sed -e "s/\$DATE/$RECEIPT_DATE/g" | sed -e "s/\$ADDRESS/$ADDRESS/g" | sed -e "s/\$AMOUNT_DUE/\$$AMOUNT_DUE/g" | sed -e "s/\$AMOUNT_PAID/\$$AMOUNT_PAID/g" | sed -e "s/\$AMOUNT_PAST_DUE/\$$AMOUNT_PAST_DUE/g" > $RENT_RECEIPT_FILE
else
	echo "No directory exists for the renter $RENTER_NAME!"
	exit 1
fi
echo "created receipt $RENT_RECEIPT_FILE..."
echo "done."
