#!/bin/sh

MODE=$1
SVN_HOME=$2
SRC_PATH=$3
DSE_PATH=$4
FILE_NAME=$5
FILE_EXT=$6
KEY_EXT=$7
KEY_EXC=$8

mkdir -p $DSE_PATH

#echo "Get installation files....[$MODE][$SVN_HOME][$SRC_PATH][$DSE_PATH][$FILE_NAM][$FILE_EXT][$KEY_EXT][$KEY_EXC]"
case $MODE in
DIR) #1 dir 
        LASTFILE=$SRC_PATH
		;;
FILE) #2 file
	KEYNAME=`echo "$FILE_NAME" | sed -e "s/\./\\\\\./g"`
	echo $KEYNAME
    REVLIST=`svn log -q  $SVN_HOME$SRC_PATH | grep "^r[0-9]" | awk -F"|" '{print $1}' | sed -e "s|r||g"`
	echo $REVLIST
	
	for REV in $REVLIST
	do 
		echo "REV:"$REV;
		echo "SVNPATH:"  $SVN_HOME$SRC_PATH;
		echo "SRCPATH:" $SRC_PATH/$KEYNAME
	    FILELIST=`svn log -r $REV -q -v $SVN_HOME$SRC_PATH | grep -v "D /" | grep "$SRC_PATH/$KEYNAME" | grep "$KEY_EXT" | awk '{print $2}'`
	    
	    for v in $FILELIST
	    do
	        LASTFILE=$v
	    	if [ -n "$KEY_EXC" ]; then
			    LASTFILE=`echo $LASTFILE | grep -v "$KEY_EXC"`
		fi

    		if [ -z "$LASTFILE" ] 
		then
    			:	
		else
    			break
    		fi
	    done

		if [ -n "$KEY_EXC" ]; then
			LASTFILE=`echo $LASTFILE | grep -v "$KEY_EXC"`
		fi

		if [ -z "$LASTFILE" ]; then
			:
		else
			break
		fi
	done
		;;
RFILE) #3 Revision file
	KEYNAME=`echo "$FILE_NAME" | sed -e "s/\./\\\\\./g"`
   	REVLIST=`svn log -q  $SVN_HOME$SRC_PATH | grep "^r[0-9]" | awk -F"|" '{print $1}' | sed -e "s|r||g"`
	
	for REV in $REVLIST
	do 
        FILELIST=`svn log -r $REV -q -v $SVN_HOME$SRC_PATH | grep -v "D /" | grep "$SRC_PATH/$KEYNAME" | grep "$KEY_EXT" | awk '{print $2}'`

	    for v in $FILELIST
	    do
	        LASTFILE=$v
	    	if [ -n "$KEY_EXC" ]; then
			    LASTFILE=`echo $LASTFILE | grep -v "$KEY_EXC"`
		    fi

    		if [ -z "$LASTFILE" ]; then
			:
    		else
    			break
    		fi
	    done

		if [ -n "$KEY_EXC" ]; then
			LASTFILE=`echo $LASTFILE | grep -v "$KEY_EXC"`
		fi

		if [ -z "$LASTFILE" ]; then
			:
		else
			break
		fi
	done
	
	arr=$(echo $LASTFILE | tr "/" "\n")
	for x in $arr
	do
		:
	done
	FILE_NAME_REV="$x"
		;;
*) # error unkown mode
    echo "error unkown mode"
    exit 1;;
esac
#echo "LASTFILE=[$LASTFILE]"
if [ -z "$LASTFILE" ]
then
    echo "error get SVN history"
    exit 1
fi

ERR=0
if [ -z "$FILE_NAME"  ];  then
    #echo "svn export -q --force $SVN_HOME$LASTFILE $DSE_PATH"
    svn export -q --force $SVN_HOME$LASTFILE $DSE_PATH
    ERR=$?
elif [ -n "$FILE_NAME_REV" ]; then
    #echo "svn export -q --force $SVN_HOME$LASTFILE $DSE_PATH/$FILE_NAME_REV"
    svn export -q --force $SVN_HOME$LASTFILE $DSE_PATH/$FILE_NAME_REV
    ERR=$?
else
    #echo "svn export -q --force $SVN_HOME$LASTFILE $DSE_PATH/$FILE_NAME$FILE_EXT"
    svn export -q --force $SVN_HOME$LASTFILE $DSE_PATH/$FILE_NAME$FILE_EXT
    ERR=$?
fi

if [ $ERR -ne 0 ]
then
        echo "error get tagging file"
        exit 1
fi
#echo "OK"


