#!/system/bin/sh

DATADATA="/data/data"
FACTORY_FOLDER="/factory"
DEBUG=0

fail()
{
  if [ $DEBUG -eq 1 ]; then
    echo "FAIL: wrong input Parameter"
  fi

  echo "FAIL"
  exit 0
}

copyfile()
{
  cp $1/* $2
  return 0
}

checkfile()
{

  if [ -e $1 ]; then
	return 0
  else
  	if [ $DEBUG -eq 1 ]; then
    	  echo FAIL: $1 is miss.
  	fi
	return 1
  fi

}

checkDirectory()
{

  if [ ! -d $1 ]; then
      if [ $DEBUG -eq 1 ]; then
        echo $1 does not exist.
      fi
	return 1
  fi
	return 0
}


UnTarOTPData()
{
  if [ ! -e "$DATADATA/$2" ]; then
    if [ $DEBUG -eq 1 ]; then
      echo FAIL: "$DATADATA/$2" dors not exist.
    fi
    return 1
  fi
  
  cd $DATADATA && busybox tar -zxf "$DATADATA/$2"

	foldername=$(echo $2|busybox awk -F"_" '{print $2}')
	copyfile $DATADATA/$foldername $FACTORY_FOLDER/
	
	rm -rf $DATADATA/$2
	rm -rf $DATADATA/$foldername/
	return 0

}

if [ $# -eq 3 ]; then
    DEBUG=1
fi

case "$1" in
  "0")
      checkDirectory $FACTORY_FOLDER
	if [ $? -eq 0 ]; then
	  UnTarOTPData $1 $2
	  if [ $? -eq 0 ]; then
    	    echo "PASS"	
			if [ -e "$DATADATA/Camera_Unique_ID" ]; then
				rm -rf "$DATADATA/Camera_Unique_ID"
			fi
	  else
    	    echo "FAIL"
	    exit 0
	  fi
	else
	  echo "FAIL"
	  exit 0
	fi
   ;;

  "1")
      checkDirectory $FACTORY_FOLDER
      if [ $? -eq 0 ]; then	
		UnTarOTPData $1 $2
		  if [ $? -eq 0 ]; then
				echo "PASS"
				if [ -e "$DATADATA/Camera_Unique_ID" ]; then
					rm -rf "$DATADATA/Camera_Unique_ID"
				fi
		  else
				echo "FAIL"
			exit 0
		  fi
	  else
		echo "FAIL"
		exit 0
	  fi
      exit 0
    ;;

  *)
  # echo Command ID wrong: 
    fail
    ;;

esac
