#!/bin/bash

#if we can't download the file or chmod, something's very wrong
set -e

#NOTE: this only works if all the right variables are exported, presumably by gnc-process

##TODO add --ifnew option - save off md5sums and compare, don't re-download

######################################################################################
# Defaults
MYEXT=''

######################################################################################
#parse command line arguments
until [ -z "$1" ]
do
  CURARG=$1
  case "$CURARG" in
    "--mod="* )        MYMOD=${CURARG#*=} ;;
    "--mod"   ) shift; MYMOD=$1 ;;
    "--tgz" )       MYEXT=".tgz";;
    "--clean" )       MYCLEAN=1;;
    "--gunzip" )       MYEXT=".gz";;
    *         )        MYFILE=$1;
  esac
  shift
done

######################################################################################
#get rid any trailing slashes if we're dealing with a directory
if [ "$MYEXT" = ".tgz" ] ; then
	MYFILE=$(echo $MYFILE| perl -pi -e 's/\/+$//')
fi

groovix-wget "$UPDATE_FILEBASE/$MYFILE$MYEXT" $MYFILE$MYEXT
if [ $? -ne 0 ] ; then
	echo "groovix-wget: ERROR saving $UPDATE_FILEBASE/$MYFILE$MYEXT to $MYFILE$MYEXT"
	exit 1
fi

if [ "$MYEXT" = ".gz" ] ; then
	gunzip -f $MYFILE$MYEXT
fi

if [  "$MYEXT" = ".tgz" ] ; then
	if [ -n "$MYCLEAN" ] && [ -d "$MYFILE" ] && [ ${#MYFILE} -ge 5 ]  ; then
		# make sure the dir were removing is really a dir and it has at least 5 characters so we don't accidentally something like /
		rm -rf $MYFILE
		# we assume that the parent directory exists on all gncget requests, no need to do any mkdirs
	fi
	tar --extract --directory `dirname $MYFILE$MYEXT` --verbose --gunzip --file $MYFILE$MYEXT
	rm $MYFILE$MYEXT
fi

if [ "$MYMOD" ]  ; then
	chmod $MYMOD $MYFILE
fi


