#!/bin/bash

# -------------------------------------------------------
# RPC Project :
# RPC_copy_rff : copy a RRF file into another, name updated
# P. Robert, LPP, 2011-03-23
# -------------------------------------------------------

appli=`basename $0`
appli36=`echo "$appli                                 " | cut -c1-36`
Narg=2

if( (test $# = 1 ) && (test $1 = -h ) ) ; then hh=1 ; else hh=0 ; fi

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : copy a RRF file into another, name updated" 
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   toto1.rff toto2.rff"
   echo "    toto1.rff : RFF source file"
   echo "    toto2.rff : RFF target file"
   echo ""
   if test $hh = 1 ; then exit 0 ; fi
   echo " $appli36 : *** ERROR ! Command aborted." >&2
   exit 1
fi

datim1=`date +%F'  '%H':'%M':'%S `
julsec1=`date +%s`

echo " -------------------------------------------------------------------"
echo " copy a RFF file into another one, and updating new FILE_NAME"

# test if source file exists
if test -f $1
   then
       echo "copy $1 into $2 ..."
   else 
       echo "*** RPC ERROR : File $1 does not exists"
       echo " $appli36 : *** ERROR ! Command aborted." >&2
       exit 2
fi

# test if source and target are different
if [ $1 == $2 ]; then
   echo "*** RPC ERROR :  source and target are the same"
   echo " $appli36 : *** ERROR ! Command aborted." >&2
   exit 3
fi


# save target file if already existing
if test -f $2
   then 
       echo "  * RPC WARNING : WARNING, $2 already existing, saved in $2.bak"
       echo "Continuation..."
       sleep 1
       mv $2 $2.bak
fi

echo "change FILE_NAME field ..."
sed -e "s/PAR FILE_NAME *(STR): /&xxxxxx/" -e "s/xxxxxx.*/$2/" $1 >$2

echo "Done !"

# end of command
# --------------

datim2=`date +%F'  '%H':'%M':'%S `
julsec2=`date +%s`
diff=`expr $julsec2 - $julsec1`

echo ""
echo " Starting time $appli : $datim1"
echo " Ending   time $appli : $datim2"
echo " Duration      $appli : $diff sec."
echo    
echo " $appli36 : NORMAL TERMINATION - time exe= $diff s." >&2 

echo " ==================================================================="

