#!/bin/bash

if [ $# != 1 ] ;then
	echo "Usage:   Create the csv file according until the specified hour[0-23]"
	echo "Example: ./create_csv.sh 8";
	exit
fi

mysql_user=`/usr/local/mssBak/script/encryption 1 "6266706d736f7a7c7b6b7f7b7f"`
mysql_pw=`/usr/local/mssBak/script/encryption 1 "2b3a392757557b697b7e7e757b777c"`


defineTable=`/usr/bin/mysql -u$mysql_user -p$mysql_pw --skip-column-names <<_EOF_
select defineTable from CDR_DB.cdrSource where isEnable=1 and key_sys_id=0 order by sysTypeNo;
_EOF_`

cur_dir=`pwd`

for table in $defineTable; do

	field_list=`/usr/bin/mysql -u$mysql_user -p$mysql_pw --skip-column-names <<_EOF_
select fieldName from CDR_DB.$table where fileOrder>0 order by fileOrder;
_EOF_`

	field_str="key_sys_id,instance,"
	for field in $field_list; do
		field_str=$field_str$field","
	done
	field_str=$field_str"srcCode"
	
	csvTable=`/usr/bin/mysql -u$mysql_user -p$mysql_pw --skip-column-names <<_EOF_
select recordTable from CDR_DB.cdrSource where defineTable='$table' and key_sys_id=0 order by sysTypeNo;
_EOF_`
	
	index=0
	while [ $index -le $1 ]
	do
		
		
		if [ $index -le 9 ] ;then
			hour="0"$index
		else
			hour=$index
		fi
		createcsvtable=$csvTable"_"$hour
		
		
		count=`/usr/bin/mysql -u$mysql_user -p$mysql_pw --skip-column-names <<_EOF_
select count(*) from CDR_DB.$createcsvtable;
_EOF_`



		outfile=$csvTable"_"`date +%Y_%m_%d`"_$hour.csv"
`/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
select $field_str into outfile '$cur_dir/$outfile' from CDR_DB.$createcsvtable;
_EOF_`


		echo "Create $outfile, record count=$count"
		
		let index+=1
	done

	
done



