#!/bin/bash
if [ $# != 5 ];
then
    echo "Usage:$0 FROM_DATE TO_DATE REPORT_NAME Email_List(comma-separated,no space) Client_Email_List"
    exit 1;
fi

FROM_DATE=$1
TO_DATE=$2
REPO_NAME=$3
EMAIL_LIST=$4
CLIENT_EMAIL_LIST=$5
FROM="support@qbrik.in (Qbrik Support)" 
LOG_PATH=$BASE_PATH/reports/report_log;
ZIP_LOG=$BASE_PATH/reports/zip_log;

DOUBLE_ENTRY_FILE_REP="PortfolioDoubleEntries"

if [ "$REPO_NAME" == "$DOUBLE_ENTRY_FILE_REP" ]
then 
   REPORT_FILE_NAME="PortfolioDoubleEntries";
fi

# Getting the last eod run date
GET_EOD_DATE=$(mysql $DB_NAME -u$DB_USER -p$DB_PASS -se "SELECT MAX(eod_last_completed_on) FROM EndOfDayCheck");
DATE=$(date -d $GET_EOD_DATE +%d-%m-%Y);
EODDATE=$(date -d $GET_EOD_DATE +%Y%m%d);
CURRDATE=$(date +%Y%m%d);

# Check EOD date lesser then current date

if [ $TO_DATE -le $EODDATE ];
then
	# Execute the  for the EOD date
	cd $BASE_PATH
	if [ -f $BASE_PATH/reports/$REPORT_FILE_NAME.$FROM_DATE.$TO_DATE.csv ];
	then
                exit 1;
	fi
	echo "Generating $REPO_NAME for $DATE ...";
	time ./yiic report $REPO_NAME --fromDate=$FROM_DATE --toDate=$TO_DATE --outputFile=$REPORT_FILE_NAME.$FROM_DATE.$TO_DATE.csv >$LOG_PATH 2>&1;
	if [ $? -ne 0 ]; 
	then 
		echo "Error generating report.......";
		cat $LOG_PATH | /usr/bin/mailx -s "Error generating $REPO_NAME from $FROM_DATE to $TO_DATE " -r "$FROM" $EMAIL_LIST 
		exit 1;
	fi
        #get Base Path Url
        BASE_PATH_URL=time ./yiic script GetBasePathUrl;
        REPORT_PATH=$BASE_PATH_URL/protected/reports;
	# Remove log report generate log file
	rm -f $LOG_PATH; 
        cd reports
	echo ;
	# compress the Portfolio Double Entries Report with zip
	echo "Compressing the generate $REPO_NAME..."
#	time gzip -k $REPORT_FILE_NAME.$FROM_DATE.$TO_DATE.csv;
        time zip -r $REPORT_FILE_NAME.$FROM_DATE.$TO_DATE.csv.zip $REPORT_FILE_NAME.$FROM_DATE.$TO_DATE.csv;
	echo ;

        if [ "$REPO_NAME" == "$DOUBLE_ENTRY_FILE_REP" ]
        then 
                REPO_NAME="Portfolio Double Entries Report";
        fi		
        echo -e "Report Name: $REPO_NAME \nFrom Date: $FROM_DATE\nTo Date: $TO_DATE \nClick here to download the report (requires login): $REPORT_PATH/$REPORT_FILE_NAME.$FROM_DATE.$TO_DATE.csv.zip " | /usr/bin/mailx -s "$REPO_NAME for $FROM_DATE to $TO_DATE" -r "$FROM" $CLIENT_EMAIL_LIST
fi
echo ;
echo "DONE";

