#!/bin/bash
CONFILE=/usr/local/omc/tools/decodeCdrCsv/resume_cdr_config
hostip=`cat $CONFILE | grep -w "RemoteIp" | awk -F "=" '{print $2}'`
ftpUserName=`cat $CONFILE | grep -w "RemoteUserName" | awk -F "=" '{print $2}'`
ftpPassword=`cat $CONFILE | grep -w "RemotePassword" | awk -F "=" '{print $2}'`
ftpDir=`cat $CONFILE | grep -w "RemoteDir" | awk -F "=" '{print $2}'`
outputDir=`cat $CONFILE | grep -w "OutputDir" | awk -F "=" '{print $2}'`
if [[ -e /tmp/csv_orig ]]
then
         rm -rf /tmp/csv_orig/*
else
	 mkdir -p /tmp/csv_orig
fi
tmpDir=/tmp/csv_orig

if [[ ! -e $outputDir ]]
then
	 mkdir -p $outputDir
fi

cdr_type_in=$1
date_time_from=$2
date_time_to=$3

j=0
echo $date_time_from > /tmp/cdr_decode_timeFrm;
time_from=`cat /tmp/cdr_decode_timeFrm | awk -F "_" '{print $1 "_" $2 "_" $3}'`
time_from_hour=`cat /tmp/cdr_decode_timeFrm | awk -F "_" '{print $4}'`
rm -rf /tmp/cdr_decode_timeFrm

echo $date_time_to > /tmp/cdr_decode_timeTo;
time_to=`cat /tmp/cdr_decode_timeTo | awk -F "_" '{print $1 "_" $2 "_" $3}'`
time_to_hour=`cat /tmp/cdr_decode_timeTo | awk -F "_" '{print $4}'`
rm -rf /tmp/cdr_decode_timeTo

if [[ "$cdr_type_in" = 'msc' || "$cdr_type_in" = 'MSC' ]]
then
	cdr_type="cdrFromMSC"
elif [[ "$cdr_type_in" = 'pps' || "$cdr_type_in" = 'PPS' ]]
then
	cdr_type="cdrFromPPS"
elif [[ "$cdr_type_in" = 'wxc1' || "$cdr_type_in" = 'WXC1' ]]
then
        cdr_type="cdrFromMSCwxc"
else
	echo "[Error] We can't decode this type:$cdr_type_in !"
	exit 0
fi

if [[ $time_to != $time_from || $time_to_hour < $time_from_hour ]]
then
	echo "[Erroe] set time error!"
	exit 0
fi 

ftp_to_get_cdrFile()
{
echo "test ftp -i -n $1"
	ftp -i -n $1 <<haha
	user $2 $3 
	binary
	lcd $4
	cd $5
	mget $6
	bye
haha
}

time_from_hour=$((10#$time_from_hour))
#echo $time_from_hour;
time_to_hour=$((10#$time_to_hour))
#echo $time_to_hour;
for ((  i = time_from_hour ;  i <= time_to_hour;  i++  ))
do	
	i=`printf "%02d\n" $i`
	if [[ $cdr_type == 'cdrFromMSCwxc' ]]
	then
		tmpname=cdrFromMSC
		fileName=${tmpname}*_${time_to}_$i.csv
	else	
		fileName=${cdr_type}*_${time_to}_$i.csv
	fi
	echo "Ftp to get $fileName"
	ftp_to_get_cdrFile $hostip $ftpUserName $ftpPassword $tmpDir $ftpDir $fileName	
	if [ ! -e $tmpDir/$fileName ]
	then
		j=$[$j + 1]
		echo "[Error] fail to get the $fileName file."
	fi
	i=$((10#$i))
done

if [ $j != $[ $time_to_hour - $time_from_hour + 1 ] ]
then
	/usr/local/omc/tools/decodeCdrCsv/cdr_decode $cdr_type $date_time_from $date_time_to $outputDir
	echo "Finish decode the cdr data!"
#	rm -rf /tmp/csv_orig/*
else
	echo " [Error] no decode the cdr data"
fi
exit 0
