#!/bin/bash

# ------------------------------------------------------------
# RPC Project :
# RPC_next_day : return date of next day, as '20070925'
# P. Robert, LPP, 2012-02-25
# ------------------------------------------------------------

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 of next day, 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 "
        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
# ----------------------------

ddn=`expr $ddc + 1 `
mmn=$mmc
yyn=$yyc

if test $ddn -gt $njm
   then 
   mmn=`expr $mmc + 1 `
   ddn=1

   if test $mmn -gt 12
      then
      yyn=`expr $yyc + 1 `
      mmn=1

      if test $yyn -gt 2058
         then 
              echo "*** error"
              echo "    year found > 2058"
              echo "$appli36 : *** ERROR ! Command aborted." >&2
              exit 4
      fi
   fi

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


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

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

echo $yyn$mmn$ddn
