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

CURR_DATE=$1
REPO_NAME=$2
EMAIL_LIST=$3
CLIENT_EMAIL_LIST=$4
FROM="support@qbrik.in (Qbrik Support)" 
LOG_PATH=$BASE_PATH/reports/report_log;
UP_LOG_PATH=$BASE_PATH/reports/upload_log;
ZIP_LOG=$BASE_PATH/reports/zip_log;
POOL_RE="poolReport"
OVERDUE_RE="overdueReport"
POOL_RECM="compressedPoolReport"
TIME_STAMP=$(date +%H%M%S);
if [ "$REPO_NAME" == "$POOL_RE" ]
then 
   REPORT_FILE_NAME="PoolReport";
fi

if [ "$REPO_NAME" == "$OVERDUE_RE" ]
then 
   REPORT_FILE_NAME="OverdueReport";
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);

# Check EOD date lesser then current date

if [ $CURR_DATE -ge $EODDATE ];
then
	# Execute the pool report for the EOD date
	cd $BASE_PATH
	if [ -f $BASE_PATH/reports/$REPORT_FILE_NAME.$EODDATE.csv ];
	then
		exit 1;
	fi
	echo "Generating $REPO_NAME for $DATE ...";
	time ./yiic report $REPO_NAME --asOfDate=$EODDATE --outputFile=$REPORT_FILE_NAME.$EODDATE.csv >$LOG_PATH 2>&1;
	if [ $? -ne 0 ]; 
	then 
		echo "Error generating report.......";
		cat $LOG_PATH | /usr/bin/mailx -s "Error generating $REPO_NAME for $EODDATE" -r "$FROM" $EMAIL_LIST 
		exit 1;
	fi
	# Remove log report generate log file
	rm -f $LOG_PATH; 
	cd reports
	echo ;

	# compress the poolreport with zip
	echo "Compressing the generate $REPO_NAME..."
	time gzip -k $REPORT_FILE_NAME.$EODDATE.csv;
	echo;

	# Transfer poolreport from local to ftp server
	echo "Uploading $REPO_NAME to FTP server...";
	time ncftpput -u $FTP_USER -p $FTP_PASS $FTP_HOST /Qbrik_data_dumps/ $REPORT_FILE_NAME.$EODDATE.csv.gz >$UP_LOG_PATH 2>&1;
	lftp sftp://shaktisftp:shakti@sftp@35.200.234.157/Qbrik_data_dumps -e "put $REPORT_FILE_NAME.$EODDATE.csv.gz; bye">$UP_LOG_PATH 2>&1;
	if [ $? -ne 0 ]; 
	then 
		cat $UP_LOG_PATH | /usr/bin/mailx -s "Error uploading file to FTP server" -r "$FROM" $EMAIL_LIST 
		exit 1;
	else
		rm -f $UP_LOG_PATH;
		if [ "$REPO_NAME" == "$POOL_RE" ]
		then 
			REPO_NAME="Static Pool Data";
		else 
			if [ "$REPO_NAME" == "$OVERDUE_RE" ] 
			then
				REPO_NAME="Overdue Report";
			fi
		fi		
		echo -e "Report Name: $REPO_NAME \nAs-of Date: $DATE \nClick here to download the report (requires login): ftp://$FTP_HOST/Qbrik_data_dumps/$REPORT_FILE_NAME.$EODDATE.csv.gz " | /usr/bin/mailx -s "$REPO_NAME for $DATE" -r "$FROM" $CLIENT_EMAIL_LIST
	fi	
fi
echo;
echo "DONE";

