#!/bin/sh

csvfile=/usr/local/measure/set/ftp.setting
localdir1=/usr/local/measure/tempdata
localdir2=/usr/local/measure/csv

#check arguments
if [ $# -ne 1 ]
	then
   		echo "指定された引数は$#個です。" 1>&2
   		echo "実行するには1個の引数が必要です。" 1>&2
   		exit 1
fi

if [ $1 -ge 5 ]
	then
  		echo "引数は 0 1 2 3 4 のいずれかのみ可" 1>&2
		exit 1
fi

#read settying file
for line in `cat $csvfile`
	do

	mch=`echo $line | cut -d ',' -f 1`
	mname=`echo $line | cut -d ',' -f 2`
	svrdomain=`echo $line | cut -d ',' -f 3`
	svrid=`echo $line | cut -d ',' -f 4`
	svrpw=`echo $line | cut -d ',' -f 5`
	tempcsv=`echo $line | cut -d ',' -f 6`
	header=`echo $line | cut -d ',' -f 7`
	log=`echo $line | cut -d ',' -f 8`
	fnh=`echo $line | cut -d ',' -f 9`
	filedist=`echo $line | cut -d ',' -f 10`
	svrdir=`echo $line | cut -d ',' -f 11`

	if test $mch -eq $1
		then
		break
	fi

done

#copy and rename data-csv file
if [ -e $localdir1/$tempcsv ]; then
	cp $localdir1/$tempcsv $localdir2/$fnh$(date +%Y%m%d%H%M).csv
fi

#make a new data-csv file with header
if [ -e $header ]; then
        cat $header > $localdir1/$tempcsv
fi

#if file distination is 1 or 3,copy to local ftpsever directory
if [ $filedist = "1" -o $filedist = "3" ]; then
	cp $localdir2/$fnh*.csv /home/aepm1
	if [ $filedist = "1" ] ; then
		rm $localdir2/$fnh*.csv
	fi
fi

#if file distination is 2 or 3,upload to FTP sever on internet
if [ $filedist = "2" -o $filedist = "3" ]; then

  cd $localdir2

  for upcsv in `ls $fnh*.csv`
    do
	#make file (FTP.TXT) for FTP uploading
	echo open $svrdomain > FTP.txt
	echo user $svrid $svrpw >> FTP.txt
	echo prompt >> FTP.txt
	echo passive >> FTP.txt
	echo ascii >> FTP.txt
	echo cd $svrdir >> FTP.txt
	echo mput $upcsv >> FTP.txt
	echo close >> FTP.txt
	echo quit >> FTP.txt

	#uplocad to FTP server on internet
	ftp -nv < FTP.txt > $log 2>&1
	sleep 1

	#error detection of FTP uoload
	grep ^226 $log > /dev/null

	if [ "$?" -eq "0" ] ; then
		# if no errores,eraze uploaded csv files. if have errores,don't erase them.
		rm $localdir2/$upcsv
	fi
	rm FTP.txt
    done

fi

cd /

exit 0
