#!/bin/sh
#
# sample UNIX script to download a GDAS analysis by FTP2U
# this script is an example how to use wwwgrab and ftp2u
#
# this sample script only downloads the 500 hPA height field
#
# usage: sample_gdas_download yyyymmddhh
#

URL="http://nomad2.ncep.noaa.gov/cgi-bin/ftp2u_gdas.sh"
email=email@nowhere.com

if [ $# -ne 1 ] ; then
  echo "usage: $0 YYYYMMDDHH"
  echo "gets GDAS analysis from $URL"
  exit 0
fi
date=$1

# run URL and parse out FTP directory

ftpdir=`wwwgrab "$URL?\
file=gdas${date}f00&\
wildcard=&\
lev_500_mb=on&var_HGT=on&\
results=SAVE&rtime=1hr&" |\
grep "Results were saved in" | sed -e 's-^.*href="ftp://--' -e 's/".*$//'`

# extract the machine and directory 
machine=`echo $ftpdir | sed 's-/.*--'`
ftpdir=`echo $ftpdir | sed 's-[^/]*/--'`
export ftpdir machine
echo "data is in ftp://$machine/$ftpdir"

if [ "$ftpdir" = '' ] ; then
   echo "failed"
   exit 9
fi

# use FTP to get the data
# Note: in the future, the ftpdir may be on a different machine
# than the web server.

ftp -v -n $machine <<EOF
user anonymous $email
bin
prompt
cd $ftpdir
mget *
EOF
