#!/bin/bash

# check environment
if [ ${GLD_ETC:-none} == none ]; then
	echo "$0: ERROR: GLD_ETC is not exported from the shell environment" > /dev/stderr
	exit 1
fi

# configurable parameters
GITHUB="https://github.com"
GITHUBUSERCONTENT="https://raw.githubusercontent.com"
COUNTRY="US"
GITUSER=slacgismo
GITREPO="gridlabd-weather"
GITBRANCH="master"
DATADIR="$GLD_ETC/weather/$COUNTRY"

# load the configuration (if any)
CONFIGFILE="$GLD_ETC/gridlabd-weather.conf"
if [ -f $CONFIGFILE ]; then
	source $CONFIGFILE
fi

function config()
{
	if [ $# == 0 -o "$1" == "show" ]; then
		echo "GITHUB=\"$GITHUB\""
		echo "GITHUBUSERCONTENT=\"$GITHUBUSERCONTENT\""
		echo "COUNTRY=\"$COUNTRY\""
		echo "GITUSER=\"$GITUSER\""
		echo "GITREPO=\"$GITREPO\""
		echo "GITBRANCH=\"$GITBRANCH\""
		echo "CACHEDIR=\"$CACHEDIR\""
		echo "DATADIR=\"$DATADIR\""
	elif [ "$1" == "reset" ]; then
		rm -f $CONFIGFILE || (echo "ERROR: unable to reset $CONFIGFILE" > /dev/stderr; exit 1)
	elif [ "$1" == "set" -a $# == 3 ]; then
		echo "$2=\"$3\"" >> $CONFIGFILE
	elif [ "$1" == "get" -a $# == 2 ]; then
		if [ ! -r $CONFIGFILE ]; then
			value=$(config show | grep $2)
		else
			value=$(grep ^$2 $CONFIGFILE | tail -n 1)
		fi
		if [ -z "$value" ]; then
			value=$(config show | grep $2)
		fi
		echo $value | cut -f2 -d= | cut -f2 -d\"
	else
		echo "'$1' is an invalid config option"
		exit 1
	fi
}

# set the internal parameters
CACHEDIR="$DATADIR/.gridlabd-weather"
GITPROJ="$GITHUB/$GITUSER/$GITREPO"
GITFILE="$GITHUBUSERCONTENT/$GITUSER/$GITREPO/$GITBRANCH"
COMMIT_ID=$(git ls-remote "$GITPROJ" | grep "$GITBRANCH" | head -n 1 | cut -f1)
INDEX=$CACHEDIR/$COMMIT_ID

function fetch_index()
{
	if [ ! -d $DATADIR ]; then
		mkdir -p $DATADIR || (echo "ERROR: unable to create $DATADIR" > /dev/stderr; exit 1)
	fi
	if [ ! -d $CACHEDIR ]; then
		mkdir -p $CACHEDIR || ( echo "ERROR: unable to create $CACHEDIR" > /dev/stderr; exit 1)
	fi
	if [ ! -f $INDEX -o -z $INDEX ]; then
		echo -n "Downloading ${GITBRANCH} index of $COUNTRY weather archive from ${GITPROJ}... "
#		svn $SVNLSOPTIONS ls $GITPROJ/branches/$GITBRANCH/$COUNTRY | grep '.tmy3$' > $INDEX || rm -f $INDEX
		curl -s $GITHUBUSERCONTENT/$GITUSER/$GITREPO/$GITBRANCH/$COUNTRY/.index >$INDEX
		echo $(wc -l $INDEX | sed -e 's/ \+/ /g;s/^ //' | cut -f1 -d' ') "weather files found"
	fi
	if [ ! -f $INDEX ]; then
		echo "$0: ERROR: unable to fetch index" > /dev/stderr
		exit 1
	fi
}

#
# command line interface
#
function help()
{	
	if [ $# == 0 ]; then
		cat <<-END
			Syntax: gridlabd weather <command> [...]
			Commands:
			  help               Get the list of weather subcommands
			  index <pattern>    Index of available weather data matching <pattern> in archive
			  list <pattern>     List of available downloaded weather data matching <pattern>
			  get <pattern>      Download weather data matching <pattern> from archive 
			  delete <pattern>   Delete downloaded weather data matching <pattern>
			  info <pattern>     Get information about weather data in <pattern>
			  clean              Clean up the local cache of the archive index
			  config show        Show the current configuration
			         reset       Reset the current configuration
			         set <N>=<V> Set configuration variable name <N> to value <V>
			         get <N>     Get configuration variable name <N>
			END
	fi
}

function clean()
{
	rm -rf $CACHEDIR 
	if [ -d $CACHEDIR ]; then
		echo "$0: ERROR: unable to delete $CACHEDIR" > /dev/stderr
		exit 1
	fi
	fetch_index
}

function index()
{
	fetch_index
	if [ $# == 0 ]; then
		cat $INDEX
	else
		grep "$1" $INDEX
	fi
}

function list()
{
	fetch_index
	for f in $(index $1); do
		if [ -f $DATADIR/$f ]; then
			echo $f
		fi
	done
}

function get()
{
	fetch_index
	for f in $(index $1); do
		if [ ! -f $DATADIR/$f ]; then
			echo -n "Downloading $f... "
			(curl -s $GITFILE/$COUNTRY/$f > /tmp/$$ && mv /tmp/$$ $DATADIR/$f && echo "done") || (echo "ERROR: unable to download $f" > /dev/stderr; rm -f /tmp/$$; exit 1)
		# else
		# 	echo -n "Refreshing $f... "
		# 	(curl -s $GITFILE/$COUNTRY/$f -z $DATADIR/$f > /tmp/$$ && mv /tmp/$$ $DATADIR/$f && echo "done") || (echo "ERROR: unable to refresh $f" > /dev/stderr; rm -f /tmp/$$; exit 1)
		fi
	done
}

function info()
{
	fetch_index
	first="yes"
	for f in $(index $1); do
		if [ -s $DATADIR/$f ]; then
			if [ "$first" == "yes" ]; then
				echo "Filepath,Country,StationId,StationName,RegionName,TzOffset,Latitude,Longitude,Elevation"
				first="no"
			fi
			echo -n "\"$DATADIR/$f\",$COUNTRY,"
			head -n 1 $DATADIR/$f
		fi
	done
}

function delete()
{
	fetch_index
	for f in $(index $1); do
		if [ -f $DATADIR/$f ]; then
			rm -f $DATADIR/$f || ( echo "ERROR: unable to delete %f" > /dev/stderr; exit 1)
		fi
	done

}

if [ $# == 0 -o "$1" == "help" ]; then
	help $2
	exit 0
elif [ "$(type -t $1)" = "function" ]; then
	$*
	exit 0
else
	echo "$0: ERROR: '$1' is not a valid weather command" > /dev/stderr
fi
