#!/bin/bash
#
# Register all files passed in command line parameters to SG
#
# Author: Gabriele Giammatteo, 2012



################################################################################
#                                                                              #
# functions declaration                                                        #
#                                                                              #
################################################################################


log_debug() {
	echo "[sg_register_all][DEBUG] $1"
}

log_info() {
	echo "[sg_register_all][INFO] $1"
}


log_error() {
	echo "[sg_register_all][ERROR] $1"
}



log_fatal() {
	echo "[sg_register_all][FATAL] $1"
}

################################################################################
#                                                                              #
# script entry point                                                           #
#                                                                              #
################################################################################


######################
# initialisation and commandline parsing
#
source $(dirname $0)/../lib/shflags

FLAGS_HELP="USAGE: $0 [flags]"
DEFINE_string 'url' '' "registration client endpoint" 'u'
DEFINE_string 'scope' '' "scope (e.g. /gcube/devsec)" 's'
DEFINE_boolean 'snapshots' false "accept snapshot versions" 'p'
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"




######################
# checks pre-requisites to run the script
#
[ -z "$GLOBUS_LOCATION" ] && log_fatal "GLOBUS_LOCATION is not set. Cannot continue, exiting..." && exit 1;
[ -z "${FLAGS_url}" ] && log_fatal "--url option not set. Cannot continue, exiting..." && exit 1;
[ -z "${FLAGS_scope}" ] && log_fatal "--scope option not set. Cannot continue, exiting..." && exit 1;



SG_WORKINGDIR=`pwd`/sgtmp
mkdir -p $SG_WORKINGDIR 2> /dev/null


source $GLOBUS_LOCATION/bin/gcore-load-env

SG_URL=${FLAGS_url}
SCOPE=${FLAGS_scope}
DRGCLASSPATH=`cat $(dirname $0)/../classpath.txt`:$(dirname $0)/../target/classes
log_info "SG_URL=$SG_URL"
log_info "SCOPE=$SCOPE"
log_info "CLASSPATH=$CLASSPATH"
log_info "DRGCLASSPATH=$DRGCLASSPATH"

#initialize distribution report
DISTRIBUTION_REPORT=`pwd`/distribution.xml
DISTRIBUTION_LOG_REPORT=`pwd`/distribution_log.xml


echo "<Packages>" > $DISTRIBUTION_REPORT


for PROFILE_FILE in "$@"; do

	#call sgclient
	java org.gcube.vremanagement.softwaregateway.client.RegisterProfileClient ${FLAGS_url} ${FLAGS_scope} $PROFILE_FILE
	EXIT_CODE=`echo $?`
	if [ $EXIT_CODE -ne 0 ]; then
		echo $PROFILE_FILE >> distribution_exceptions.txt
		continue
	fi
	
	PROFILE_NAME=`basename $PROFILE_FILE.xml`
	REPORT_FILE=$SG_WORKINGDIR/report_$PROFILE_NAME.xml
	cat report.xml  | sed 's/&/&amp;/g' > $REPORT_FILE
			
	cat $REPORT_FILE | sed '1d' | sed '$d' >> $DISTRIBUTION_REPORT

done

echo "</Packages>" >> $DISTRIBUTION_REPORT
