#!/usr/bin/ksh
#
# wget_green_gmag.ksh
#
# Author: Patrick Cruce(pcruce@igpp.ucla.edu)
#
# Based heavily on wget_nrsq_gmag.ksh and wget_maccs_gmag.ksh by Tim Quinn(teq@ssl.berkeley.edu)
#
# $1 = site
# $2 = year
# $3 = month
# $4 = day
#
## Set environment variables
#
  if [[ -z $THMSOC ]]
  then
    THMSOC=/disks/socware/thmsoc_dp_current
    export THMSOC
  fi
	. $THMSOC/src/config/soc_it_to_me.config
	. $THMSOC/src/config/wget_green_gmag.config

#
## Handle input arguments
#
site=${1}
year=${2}
month=${3}
day=${4}

#
## Set logfiles
#
	processdate=$(date '+%y%m%d')
	LOGFILE=${LOGDIR}/webdownloads/green_gmag_log_${processdate}_$$
	WGETLOG=${LOGDIR}/webdownloads/wget_output_green_gmag_${processdate}_$$

	echo ":$$:green_gmag_log:" >> $LOGFILE
	echo ":$$:green_gmag_log:Starting script wget_green_gmag at $(date)" >> $LOGFILE

#
## Run wget to download data from Greenland GMAG Network
#

        filename=green_${site}_${year}${month}${day}.html
	wgetTime=$(date '+%Y-%m-%d %T')
	url=${WEBSITE}\?site=${1}\&year=${2}\&month=${3}\&day=${4}\&${WEBOPTS}
	outfile=${LOCALWEBMIRROR}/${filename}
	/usr/bin/wget -r -l 1 -nd -N -o $WGETLOG -O $outfile $url
	
	echo ":$$:green_gmag_log: Download Complete: $site" >> $LOGFILE
#
## Parse through wget output to see what was downloaded
#

	# Verify file exists
	if [[ ! -a ${outfile} ]]
	then
    	  echo "$$:green_gmag_log:" >> $LOGFILE
    	  echo "$$:green_gmag_log: ${outfile} not found. " >> $LOGFILE
	  exit 1
        fi

        grep -i "error" ${WGETLOG} >> /dev/null                 
        if [[ $? -eq 0 ]]
	then
	  echo "$$:green_gmag_log:" >> $LOGFILE
    	  echo "$$:green_gmag_log: ${outfile} download error" >> $LOGFILE
          rm -f ${outfile}
	  exit 1
	fi

#		fileSize=$(echo $size |awk -F/ '{print $2}')
#		fileSize=${fileSize%*\]}

		# Update database with stats
#		${PHP_SCRIPTS}/wget_nrsq_gmag.php $fileName $wgetTime $fileTime $fileSize

		# Create a file used for CDF processing
#		touch ${GMAGMIRROR}/$fileName


exit 0
