#!/bin/bash

if [ "$1+" == "+" ] ;then
	export_dir=/usr/local/apache/htdocs/db_backup/csta
else
	export_dir=$1
	if [ ! -d $export_dir ] ;then
		export_dir=/usr/local/apache/htdocs/db_backup/csta
	fi
fi

echo export_dir=$export_dir
exit

## Get the last date of last day
# Get the current date
month=`date +%m`
day=`date +%d`
year=`date +%Y`
hour=`date +%H`

to_year=$year
to_month=$month
to_day=$day
to_hour=$hour


iHour=`expr $hour - 1`
if [ $iHour -eq -1 ]; then
iHour=23
day=`expr $day - 1`
fi

if [ $day -eq 0 ]; then
month=`expr $month - 1`
# If the month is 0 then it is Dec 31 of the previous year
if [ $month -eq 0 ]; then
month=12
day=31
year=`expr $year - 1`
# If the month is not zero we need to find the last day of the month
else
case $month in
1|3|5|7|8|10|12) day=31;;
4|6|9|11) day=30;;
2)
if [ `expr $year % 4` -eq 0 ]; then
if [ `expr $year % 400` -eq 0 ]; then
day=29
elif [ `expr $year % 100` -eq 0 ]; then
day=28
else
day=29
fi
else
day=28
fi
;;
esac
fi
fi

monthstr=$month
case $month in
1|2|3|4|5|6|7|8|9) monthstr="0"$month;;
esac

daystr=$day
case $day in
1|2|3|4|5|6|7|8|9) daystr="0"$day;;
esac

hourstr=$iHour
case $iHour in
1|2|3|4|5|6|7|8|9) hourstr="0"$iHour;;
esac


from_year=$year
from_month=$monthstr
from_day=$daystr
from_hour=$hourstr

#echo from $from_year-$from_month-$from_day $from_hour to $to_year-$to_month-$to_day $to_hour
from_time_str=$from_year"-"$from_month"-"$from_day" "$from_hour":00:00"
to_time_str=$to_year"-"$to_month"-"$to_day" "$to_hour":00:00"

mysql_user=`/usr/local/mssBak/script/encryption 1 "627273706e69687c727979"`
mysql_pw=`/usr/local/mssBak/script/encryption 1 "6f716c7866697074795a4c2f434639"`


if [ -f ./csta_system.conf ] ;then

	syslist=`cat ./csta_system.conf`
	for sys in $syslist; do

genFileName="${sys}Detail_"$from_year"_"$from_month"_"$from_day"_"$from_hour".csv"
fromTableName="${sys}DetailData"
generalSql="SELECT * INTO OUTFILE '$export_dir/$genFileName' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n' FROM CSTA_DB.$fromTableName WHERE csta_datetime>='$from_time_str' AND csta_datetime<'$to_time_str' "

`/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
$generalSql;
_EOF_`

	done

else
genFileName="mscDetail_"$from_year"_"$from_month"_"$from_day"_"$from_hour".csv"
fromTableName="mscDetailData"
generalSql="SELECT * INTO OUTFILE '$export_dir/$genFileName' FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\n' FROM CSTA_DB.$fromTableName WHERE csta_datetime>='$from_time_str' AND csta_datetime<'$to_time_str' "

`/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
$generalSql;
_EOF_`

fi

