#!/bin/bash

######################################################################################
#parse command line arguments
until [ -z "$1" ]
do
  CURARG=$1
  case "$CURARG" in
    "--upgrade")        MYUPGRADE=1  ;;
  esac
  shift
done
######################################################################################


if [ -z "$CURARG" ] ; then
	echo "usage: $0 [--upgrade] gnc-name"
	exit 1
fi

MYNAME=$CURARG

echo $MYNAME | egrep "gnc$" > /dev/null
if [ $? -eq 0 ] ; then
	GNCF=$MYNAME
else
	GNCF=$MYNAME/gnc
fi

if ! [ -e $GNCF ] ; then
	echo "invalid dir specified , $GNCF does not exist"
	exit 1
fi

#get old GNC_ORDER from file
#eval $(egrep "^GNC_ORDER=" $GNCF | head -n 1)
OLD_GNC_DATE_ORDER=$(cat $GNCF | perl -n -e 'if (/^GNC_ORDER=(20\d{6}\.?\d*)/) { print $1 }')

#if not a date order
if [ -z "$OLD_GNC_DATE_ORDER" ] ; then
	# it was a specific order, keep it and any decimal places if less than 8 decimal places which is probably another date
	OLD_GNC_ORDER=$(cat $GNCF | perl -n -e 'if (/^GNC_ORDER=(\d+\.?\d{0,7}\b)/) { print "$1$2$3" }' | sed 's/\.$//' )
	# it was fixed number order based, just tack on current date for refresh but keep it in same order
	MYORDER=$OLD_GNC_ORDER.$(date +%Y%m%d.%H%M%S)
else
	# it was date based, use current date 
	if [ -n "$MYUPGRADE" ] ; then
		#if using gnc-to-2013 we want customer gncs to usually run AFTER default groovix-2013 gncs (unless they had a specific order number set)
		# but keep their order amongst themselves
		MYORDER=$(date +%Y%m%d).$OLD_GNC_DATE_ORDER
	else
		MYORDER=$(date +%Y%m%d.%H%M%S)
	fi
fi

sed -i "s/GNC_ORDER=.*/GNC_ORDER=$MYORDER/" $GNCF
