#!/bin/sh
# Prints date and time in D. E. Shaw & Co. standard format, can go back
# a day if necessary as a special hack for scripts that run in the wee
# hours of the morning to parse/generate log files.

# Kimmo Suominen, D. E. Shaw & Co.

PATH=/usr/pkg/bin:/bin:/usr/bin:/usr/ucb
export PATH

usage="Usage: $0 [-d days|-m months] [-p] [-u]"
doff=0
moff=0
previous=n
utc=
while getopts d:m:pu opt
do
    case "$opt" in
    d)	doff="$OPTARG";;
    m)	moff="$OPTARG";;
    p)	previous=y;;
    u)	utc="-u";;
    *)	echo $usage >&2; exit 1;;
    esac
done

set x `date $utc '+%Y %m %d %H %H:%M:%S'`

year=`expr $2 + 0`
month=`expr $3 + 0`
day=`expr $4 + 0`
hour=`expr $5 + 0`
time=$6

if [ "$previous" = "y" -a "$hour" -le 8 ]
then
    doff=`expr $doff + 1`
fi

if [ $doff -gt 0 ]
then
    day=`expr $day - $doff`
fi

if [ $moff -gt 0 ]
then
    yoff=`expr $moff / 12`
    year=`expr $year - $yoff`
    moff=`expr $moff - $yoff \* 12`
    month=`expr $month - $moff`
fi

if [ $day -lt 1 ]
then
    month=`expr $month - 1`
    day=`expr $day + 31`
fi

if [ $month -lt 1 ]
then
    year=`expr $year - 1`
    month=`expr $month + 12`
fi

maxdays=31
case `expr $month + 0` in
2)
    if [ \( `expr $year % 4` -eq 0 -a `expr $year % 100` -gt 0 \) \
	-o `expr $year % 400` -eq 0 ]
    then
	maxdays=29
    else
	maxdays=28
    fi
    ;;
4|6|9|11)
    maxdays=30
    ;;
esac

if [ $day -gt $maxdays ]
then
    day=$maxdays
fi

printf "%04d%02d%02d %s\n" $year $month $day $time
