#! /bin/ksh

# This script copies GFS input files from a remote machine via scp and
# links some of them to the OCEAN directory.  It assumes all needed
# files already exist.

set -x -u -e

gdasdir=''   # if non-empty, where to find GDAS (only used for satang file)
wait_grib=no  # if yes, wait for the first grib file to appear
firstgrib=0
lastgrib=0
gribstep=6

firstsf=0
lastsf=126
sfstep=6

function arg {
    if [[ ! ( "$2" -gt 1 ) ]] ; then
        echo "ABORTING.  $1 requires an argument."
        return 2
    fi
}

go=yes
while [[ "$go" == yes && "$#" -gt 0 ]] ; do
    case "$1" in
        --all-gribs)                   lastgrib=126    ; shift 1 ;;
        --gdas-satang) arg "$1" "$#" ; gdasdir="$2"    ; shift 2 ;;
        --)                            go=no           ; shift 1 ;;
        *)                             go=no                     ;;
    esac
done

cycle="$1"   # cycle (YYYYMMDDHH)
wind="$2"    # where to put or link wind data
ocean="$3"   # where to put or link ocean data
gfsdir="$4"  # where to find GFS input (user@host:/path/to/gfs/data)

ln='ln -sf'
hh=$( echo "$cycle" | cut -c9-10 )
orig=$wind/gfs.t${hh}z
here=gfs.t${hh}z

cd "$wind"

scp -p "$gfsdir" .

if ( ! echo "${GFS_SOURCE:-}" | grep -i grib2 ) ; then
    # Make symbolic links to operational naming convention files
    # if the misnamed ones are present.  
    for fh in $( seq $firstgrib $gribstep $lastgrib ) ; do
        fh00=$( printf "%02d" $fh )
        # The grib files can have two different naming conventions:
        opername=$orig.pgrbf$fh00              # operational naming convention
        misnamed=$wind/pgrbf$fh00.gfs.$cycle   # misnamed in some retrospectives
        if [[ -e "$misnamed" && ! -e "$opername" ]] ; then
            $ln $misnamed $here.pgrbf$fh00
        fi
    done
fi

# Also link the sanl and sfcanl files to the spinup directory
cd "$ocean"
$ln $orig.sanl $here.sanl
$ln $orig.sfcanl $here.sfcanl

exit 0
