#! /bin/sh

# Create a new input directory INPUT-YYYMMDD from the current
# INPUT directory and the files in RESTART/*.res*

# For compatibility with the restart.sh from Markus, we also accept
# two optional parameters:
old="$1"
new="$2"
if [ -n "$3" -o \( -n "$old" \) -a \( -z "$new" \) ]
then
    echo "$0: need zero or two parameters (old and new INPUT- suffix)"
    exit 40
fi

parsedate () { # for splitting the lastline of coupler.res into words
    year06="`printf '%06d' $1`"
    month02="`printf '%02d' $2`"
    day02="`printf '%02d' $3`"
}

if [ ! -h INPUT ]
then
    echo "$0: INPUT is not a symbolic link. Dont know how to proceed."
    exit 41
fi
# lrwxrwxrwx 1 petri climber3    14 Jan 28 13:00 INPUT -> INPUT-00220101
if [ -n "$old" ]
then
    oldINPUT=INPUT-$old
else
    oldINPUT=`ls -ld INPUT | awk '{print $11;}'`
fi
if [ ! -d "$oldINPUT" ]
then
    echo "$0: Cannot find old INPUT directory $oldINPUT ."
    exit 42
fi
echo "Found current INPUT directory $oldINPUT ."
#exit

if [ -n "$new" ]
then
    newINPUT=INPUT-$new
else
#     4        (Calendar: no_calendar=0, thirty_day_months=1, julian=2, gregorian=3, noleap=4)
#     1     1     1     0     0     0        Model start time:   year, month, day, hour, minute, second
#    32     1     1     0     0     0        Current model time: year, month, day, hour, minute, second
    if [ ! -f RESTART/coupler.res ]
    then
	echo "$0: no file RESTART/coupler.res"
	exit 43
    fi
    nlines="`wc -l < RESTART/coupler.res`"
    if [ 3 -ne 0"$nlines" ]
    then
	echo "$0: RESTART/coupler.res should have 3 lines but has $nlines ."
	exit 44
    fi
    lastline="`tail -1 RESTART/coupler.res`"
    parsedate $lastline
    newINPUT="INPUT-$year06$month02$day02"
fi
echo "Trying to create new directory $newINPUT"

if [ -d "$newINPUT" ]
then
    echo "$0: A directory named $newINPUT already exists. Will not overwrite it."
    exit 45
fi
if [ -h "$newINPUT" ]
then
    echo "$0: A symbolic link named $newINPUT already exists. Will not overwrite it."
    exit 46
fi
if [ -e "$newINPUT" ]
then
    echo "A filexs  named $newINPUT already exists. Will not overwrite it."
    exit 47
fi
mkdir "$newINPUT" || exit 48
echo "Copying contents of $oldINPUT into $newINPUT"
cp -a "$oldINPUT/"* "$newINPUT"
echo "moving RESTART files into $newINPUT"
( cd RESTART
  for i in *.res* ; do rm ../"$newINPUT"/$i ; mv $i ../"$newINPUT"/$i ; done
)
echo "Creating new symlink INPUT -> $newINPUT"
rm INPUT
ln -s "$newINPUT" INPUT
echo "Done"
