#! /bin/bash

if [ $# -ne 2 ]; then
    echo '$1 is stations.txt file'
    echo '$2 is daily or monthly'
    exit 1
fi

function try1 {
    mimax=$1
    mcode=$2
    display1=$3
    display2=$4

    echo Get $mimax $id $name
    #echo wget --output-document=freddoc 'http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_nccObsCode='$mcode'&p_display_type='$display1'&p_startYear=&p_c=&p_stn_num='$id
    wget --output-document=freddoc 'http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_nccObsCode='$mcode'&p_display_type='$display1'&p_startYear=&p_c=&p_stn_num='$id > /dev/null 2>&1
    code="`egrep -m 1 -o '&amp;p_c=[^&]+' freddoc`"
    fail=$?
    rm freddoc > /dev/null 2>&1

    if (( ! $fail )); then
        # we have a valid code
	code="${code:5}"
	echo $id $name "($mimax)" p_nccObsCode=$mcode ':' $code
	dname="${name// /_}"
	dname="${dname//(/}"
	dname="${dname//)/}"
	fname="BOM-${id}-${dname}-${when}-${mimax}.zip"
	echo '    p_stn_num='$id'&'$code'&p_nccObsCode='$mcode

	# echo wget -q --output-document="$fname" 'http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_display_type='$display2'&p_stn_num='$id'&'$code'&p_nccObsCode='$mcode
	wget -q --output-document="$fname" 'http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_display_type='$display2'&p_stn_num='$id'&'$code'&p_nccObsCode='$mcode

	return 0
    fi

    return 1
}

when="$2"
mmm="$3"

if [ "$when" = daily ]; then
    htmltype='dailyDataFile'
    ziptype='dailyZippedDataFile'
    maxocode=122
    minocode=123
elif [ "$when" = monthly ]; then
    htmltype='dataFile'
    ziptype='monthlyZippedDataFile'
    maxocode=36
    minocode=38
else
    echo "Bad frequency: $2" >&2
    exit 1
fi


cut -c 2-7,15-54 "$1" | while read ln; do
    id="${ln:0:6}"
    name="${ln:6:40}"
    if [[ $id =~ [0-9]{6} ]]; then
	rm freddoc > /dev/null 2>&1

	# maximum
	try1 max $maxocode $htmltype $ziptype

	# minimum
	if (( ! $? )); then
	    try1 min $minocode $htmltype $ziptype
	fi
    fi
done
