#!/bin/bash

# ------------------------------------------------------------
# RPC Project :
# RPC_previous_day : return date one day before, as '20070925'
# P. Robert, LPP, 2011-03-24
# ------------------------------------------------------------

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

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

if test $# != $Narg || test $hh = 1
   then
   echo "$appli : return date one day before, as '20070925'"
   echo "$appli   require $Narg argument(s), ex:"
   echo "$appli   date"
   echo "    ex: $appli 20070925"
   echo ""
   if test $hh = 1 ; then exit 0 ; fi
   echo "$appli36 : *** ERROR ! Command aborted." >&2
   exit 1
fi


datec=$1

yyc=`echo $datec | cut -c1-4`
mmc=`echo $datec | cut -c5-6`
ddc=`echo $datec | cut -c7-8`

# check input date validity
# -------------------------

njm=`RPC_nday_of_month $yyc $mmc`
if test $? != 0 
   then 
        echo "njm=$njm "
        echo "$appli36 : *** ERROR ! Command aborted." >&2
        exit 2 
fi

if ((test $ddc -lt 1) || (test $ddc -gt $njm ))
    then 
        echo "day of month must be >= 1 and =< $njm"
        echo ""
        echo "$appli36 : *** ERROR ! Command aborted." >&2
        exit 3
fi

# compute date of previous day
# ----------------------------

ddp=`expr $ddc - 1 `
mmp=$mmc
yyp=$yyc

if test $ddp -lt 1
   then 
   mmp=`expr $mmc - 1 `

   if test $mmp -lt 1
      then
      yyp=`expr $yyc - 1 `
      mmp=12

      if test $yyp -lt 1972
         then 
              echo "*** error"
              echo "    year found < 1972"
              echo "$appli36 : *** ERROR ! Command aborted." >&2
              exit 4
      fi
   fi

   if test $mmp -lt 10 ; then mmp=0$mmp ; fi
   ddp=`RPC_nday_of_month $yyp $mmp`
   if test $? != 0 
      then 
           echo "$ddp "
           exit 5 
   fi
fi   


if test $ddp -lt 10 ; then ddp=0$ddp ; fi

# return date of previous day
# ---------------------------

echo $yyp$mmp$ddp
