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

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

wwwgrab=wwwgrab
wwwgrab="wget --output-document=- -q"

if [ $# -ne 1 ] ; then
  echo "usage: $0 YYYYMMDD"
  echo "gets daily ave CDAS analysis"
  exit 0
fi
date=$1

# run URL and parse out FTP directory
ftpdir=`$wwwgrab "$URL?\
file=pgb.${date}&\
wildcard=&\
lev_500_mb=on&var_HGT=on&var_TMP=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
