#! /bin/bash
################################################################################
# Filename: ./src/base/bin/qrm-cli
# 
# The contents of this file are subject to the Qlusters Public License
# Version 1.1 (the License); you may not use this file except in compliance
# with the License.
# You may obtain a copy of the License at
# http://www.openqrm.org/content/view/33/69/.
# 
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
# 
# The Original Code is openQRM.
# 
# The Initial Developer of the Original Code is Qlusters Corporation. Portions
# created by Qlusters Corporation are Copyright (C) 2003-2005. All Rights
# Reserved.
# 
# Contributor(s):
# 
# Description:
# 
# Comments:
################################################################################
### ====================================================================== ###
##                                                                          ##
##  QRM-script which sends service (tags, policies..) commands to QRM       ##
##                                                                          ##
##                                                                          ##
### ====================================================================== ###

### ====================================================================== ###
# Error codes mapping:
# E_NOT_HANDLED = -1;
# E_OK = 0;
# E_SERVER_ERROR = 1; // when the server can't be reached by the client script
# E_SYSTEM_BROKEN = 2; // internal qrm exception, usually du e some inconsistency
# E_EXCEPTION = 3; // General exception
# E_USAGE = 4; // usage error
# E_AUTHORIZATION = 5; 
# E_OBJECT_NOT_FOUND = 6;
# E_OBJECT_EXISTS = 7;
# E_OBJECT_USED = 8; // cannot update object - it is in use currently
if [ -n "$QRM_DEBUG" ]; then
	set -x
fi
### ====================================================================== ###
# Usage example: ./qrm_cli event -k Node.Action.Reboot -t "\"message=force now;timeout=1\"" -i 86 -v oracle
encodings=(
        "'~' '%7E'"
        "'!' '%21'"
        "'@' '%40'"
        "'\\#' '%23'"
        "'$' '%24'"
        "'^' '%5E'"
        "'&' '%26'"
        "'\\*' '%2A'"
        "'(' '%28'"
        "')' '%29'"
        "'+' '%2B'"
        "'|' '%7C'"
        "'{' '%7B'"
        "'}' '%7D'"
        "':' '%3A'"
        "'\"' '%22'"
        "'<' '%3C'"
        "'>' '%3E'"
        "'\\?' '%3F'"
        "'\`' '%60'"
        "'=' '%3D'"
        "'\\' '%5C'"
        "'[' '%5B'"
        "']' '%5D'"
        "';' '%3B'"
        "\' '%27'"
        "',' '%2C'"
        "'/' '%2F'"
        "' ' '%20'"
        )

function final_exit(){
	/bin/rm -f $TMP_FILE
	/bin/rm -f $TMP_ERR
	/bin/rm -f $TMP_FILE.rc
	exit $1
}

function url_encode() {
        # notice : "%", "*" and "\" are not supported
        STR=$1
        STR=${STR//\\%/%7E}
        for (( i=0 ; i<${#encodings[*]} ; i++ )); do
                eval ENC=(${encodings[i]})
                STR=${STR//${ENC[0]}/${ENC[1]}}
        done
        printf "%b" "$STR"
}

# for (( i=0 ; i < $# ; i++ )); do
#       case `eval echo '$'$i` in
#               -q|--qrm)
#                       HOST=`eval echo '$'$((i+1))`
#                       ;;
#       esac
# done
#create command line
#PORT=${PORT:-8080} - 8080 doesn't support https. in any case, this isn't a performance issue
PROTOCOL=http
eval `cat /proc/cmdline` 2> /dev/null
HOST=$qrm

. /var/qrm/conf/node-parameter.conf 2> /dev/null 1>&2 
HOST=${HOST:-$QRM_SERVER_IP_ADDRESS} #can be also from env

HOST=${HOST:-localhost}

while [ $# -gt 0 ]; do
	case $1 in
       		-q|--qrm)
               		HOST=$2
        	        shift	
               		;;
		-r|--protocol)
			PROTOCOL=$2
			shift
			;;
		*)
			break;
			;;
	esac
	shift
done


URL_ARGS=''
while [ $# -gt 0 ]; do
        PARAM=`url_encode "$1"`
        URL_ARGS="${URL_ARGS}arg=$PARAM&"
        shift
done

WGET="/usr/bin/wget "
if [ "$PROTOCOL" == "https" ] && wget --help | grep 'no-check-certificate' > /dev/null; then
	WGET="$WGET ----no-check-certificate"
fi
URL_FORMAT="$PROTOCOL://${HOST}/cli?%b"

#format wget request
REQUEST=`printf $URL_FORMAT $URL_ARGS`

TMP_FILE=`mktemp -q /tmp/cli.XXXXXX`
TMP_ERR=`mktemp -q /tmp/cli_err.XXXXXX`
if ! $WGET -O $TMP_FILE $REQUEST 2> $TMP_ERR; then               # put response in tmp file for future analys
	tail -1 $TMP_ERR
	echo "ERROR: could not contact server (did you forget to use -q to specify the qrm server's ip?)" 1>&2
	final_exit 1;
fi 

RC=
#cat $TMP_FILE | while read line; do
#	prefix=`expr match "$line" '\(ERROR\|WARN\|FATAL\):'`
#	if [ "$?" -eq 0 ]; then
#		echo "$line" 1>&2
#	else
#		_rc=`expr match "$line" 'RC=\(.*\)$'`
#		if [ "$?" -eq 0 ]; then
#			echo $_rc > $TMP_FILE.rc
#		else 
#			echo "$line"
#		fi
#	fi
#done

cat $TMP_FILE | awk '/RC=/ {exit substr($0,4)} /(ERROR|WARN|FATAL):/ {print $0 > "/dev/stderr" ; next} {print $0}'
#final_exit `cat $TMP_FILE.rc |  tr -d "\r"`
final_exit $?
