#!/bin/bash

function="next"
if [ "$1" != "" ]; then	#$1 # next/walkDirect/close
	function=$1
fi
url="http://demo.q-matic.es:9094"
if [ "$2" != "" ]; then	#$2	# url
	url=$2
fi
branchId="1"
if [ "$3" != "" ]; then	#$3 # <eeetttt> e:company code / t:shop code
	branchId=$3
fi
group="PESCADERIA"
if [ "$4" != "" ]; then	#$4 # counter code
	group=$4
fi
userName="usuario1"
if [ "$5" != "" ]; then	#$5 # <eeettttvvvv><vendor_name> e:company code / t:shop code / v:vendor code
	userName=$5
	userName=${userName// /%20}
fi
crmId="0010001010115123100012"
if [ "$6" != "" ]; then	#$6 # <????????????>
	crmId=$6
fi

queryType="POST"
if [ "$function" == "close" ]; then
	queryType="PUT"
	fullURL="$url/retail/branches/$branchId/servicePoints/groups/$group/users/$userName/$function/$crmId"
else
	fullURL="$url/retail/branches/$branchId/servicePoints/groups/$group/users/$userName/$function"
fi


log="/home/pcscale/scale/log/qmatic.log"
echo -- $(date +"%x %X") -- QUERY: >> $log
echo $queryType -- $fullURL >> $log
echo ----------------------- ANSWER: >> $log
answer=$(curl -si -m 4 -X $queryType $fullURL) 
if [ $? -eq 0 ]; then
	userState=$(echo $answer  | grep -Po '"userState":.*?[^\\]"' | awk -F':' '{print $2}' | tr -d '"')
	
	echo $(echo $answer | grep branchId) >> $log
	echo " " >> $log
	
	if [ "$function" == "next" ]; then
		ticketId=$(echo $answer  | grep -Po '"ticketId":.*?[^\\]"' | awk -F':' '{print $2}' | tr -d '"')
		if [ "$userState" == "INACTIVE" ]; then
			echo "---"
			exit 0
		fi
		echo $ticketId
		exit 0
	fi
	exit 0
fi
echo Error!!! No answer. >> $log
echo " " >> $log
exit 1
