#!/bin/sh -e

# check input arguments and print help blurb if check fails
if [[ $# -lt 5 || $1 == "-h" || $1 == "--help" ]]
then
cat <<EOF

Usage: 

  $0  <output dir> <exp> <table> <ripf|subexp-ripf> <field>  

Examples: 

1. Download monthly psl from first member of historical experiment, do not create directories

  export CREATE_DIRS=false ; $0 /scratch/$USER historical Amon r1i1p1f1 psl  

2. Download monthly psl from s2000 hindcast for all members, create directories 

  export CREATE_DIRS=true ; $0 /scratch/$USER dcppA-hindcast Amon s2000-.\* psl  

3. Download daily and monthly psl for all start dates for member 1, create directories

  export CREATE_DIRS=true ; $0 /scratch/$USER dcppA-hindcast .\* .\*-r1i1p1f1 psl

4. Download daily and monthly psl for all start dates for all members, create directories

  export CREATE_DIRS=true ; $0 /scratch/$USER dcppA-hindcast .\* .\* psl

EOF
  exit 1
fi

ODIR=$1
EXPERIMENT=$2
TABLE=$3 
RIPF=$4 
FIELD=$5 

: ${CREATE_DIRS:=false}
OPTIONS='--no-use-server-timestamps -c' ; if $CREATE_DIRS ; then OPTIONS=$OPTIONS' -x -nH --cut-dirs=4' ; fi

OPTIONS='--no-use-server-timestamps -c -x -nH --cut-dirs=4'
FILELIST=urls_norcpm1_cmip6.txt
FILELIST_URL="https://ns11071k.web.sigma2.no/seaclim/wp2/"$FILELIST

mkdir -p $ODIR
cd $ODIR
[ ! -e $FILELIST ] && wget -c $FILELIST_URL 

for FILE in `cat $FILELIST | grep "/${EXPERIMENT}/" | grep "/${TABLE}/" | grep "/${RIPF}/" | grep "/${FIELD}/"`
do
  echo $FILE
  wget $OPTIONS $FILE 
done
echo DONE
