#!/bin/bash
# -------------------------------------------------------
# RPC Project :
# RPC_download_data_oneday_CLUPOS : get POS data from CAA
# P. Robert, LPP, 2012-08-25
# -------------------------------------------------------

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

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

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : get entire day of POS data from CAA"
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   SatNum year month day"
   echo "    ex: $appli 1 2001 09 23"
   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`

SatNum=$1
year=$2
month=$3
day=$4


# Spacecraft test
# ---------------

if ((test $SatNum -lt 1 ) || (test $SatNum -gt 4 ))
   then 
        echo "S/C # must be >=1 and =< 4"
        echo " $appli36 : *** ERROR ! Command aborted." >&2
        exit 2
fi


echo " ---------------------------------------------------------------------"
echo " RPC_CLUPOS_download_data_oneday: dowload an entire day of CLUSTER/POS"
echo "                                  data for time resolution=$Mode"
echo "                                  Day choosen : $year"-"$month"-"$day "
echo ""

date1=$year$month$day
date2=`RPC_next_day $date1`
if test $? != 0 
   then 
   echo " $appli36 : *** error on $year$month$day"
   echo " $appli36 : *** ERROR ! Command aborted." >&2
   exit 4
fi
year2=`echo $date2 | cut -c1-4`
month2=`echo $date2 | cut -c5-6`
day2=`echo $date2 | cut -c7-8`
echo $date1 $date2 $year2 $month2 $day2

datim_deb=$year"-"$month"-"$day"T00:00:00.000Z"
datim_fin=$year2"-"$month2"-"$day2"T00:00:00.000Z"

echo "time span: $datim_deb $datim_fin "


echo "Download data for S/C $SatNum"
echo "-----------------------"
RPC_download_data_CLUPOS $SatNum $datim_deb $datim_fin 

if test $? = 0 
   then
#  rename file
#  C1_CP_AUX_POSGSE_1M__20100101_000000_20100102_000000 in C1_CP_AUX_POSGSE_1M__20100101.cef

   dataset_id="C"$SatNum"_CP_AUX_POSGSE_1M"
   main_name=$dataset_id"__"$date1"_000000_"$date2"_000000.cef"
   new_name=$dataset_id"__"$date1.cef

   mv $main_name $new_name
   echo "file=$new_name"
 
   else
   echo " $appli36 : *** download for S/C $SatNum  $year $month $day aborted !"
   echo " $appli36 : *** BAD TERMINATION for S/C $SatNum   $year $month $day" >&2
   echo "-----------------------------------"
   exit 5
fi   

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 " ==================================================================="

