#!/bin/sh
#
# $Id$
#
# control tool for maintaining Kamailio
#
#===================================================================

##### ----------------------------------------------- #####
### ORACLE specific variables and functions
#
SESSOPT="set term off feed 0 lin 8000 pages 50000 ver off colsep '|'
col count(*) jus l format 'tm'
alter session set nls_date_format='DD-MM-RR HH24:MI:SS';
"

##### ----------------------------------------------- #####
### load SQL base
#
if [ -f "$MYLIBDIR/kamctl.sqlbase" ]; then
	. "$MYLIBDIR/kamctl.sqlbase"
else
	echo "Cannot load SQL core functions '$MYLIBDIR/kamctl.sqlbase' - exiting ..."
	exit -1
fi

if [ -f "$MYLIBDIR/kamdbfunc.oracle" ]; then
	. "$MYLIBDIR/kamdbfunc.oracle"
else
	echo "Cannot load ORACLE core functions '$MYLIBDIR/kamdbfunc.oracle' - exiting ..."
	exit -1
fi

##### ----------------------------------------------- #####
### binaries
if [ -z "$SQLPLUS" ] ; then
	locate_tool sqlplus
	if [ -z "$TOOLPATH" ] ; then
		echo "error: 'sqlplus' tool not found: set SQLPLUS variable to correct tool path"
		exit
	fi
	SQLPLUS="$TOOLPATH"
	export SQLPLUS
fi

if [ -z "$KAMAILIO_ORASEL" ] ; then
	locate_tool kamailio_orasel
	if [ -n "$TOOLPATH" ] ; then
		KAMAILIO_ORASEL="$TOOLPATH"
		export KAMAILIO_ORASEL
	fi
fi

##### ----------------------------------------------- #####

# input: sql query, optional sqlplus command-line params
oracle_query() {
	# if password not yet queried, query it now
	prompt_oracle_pw rw
	mdbg "oracle_query: $SQLPLUS $2 -S -L -R 3 $DBRWUSER@$DBNAME '$1'"
	RC=`echo "$SESSOPT $1" | $SQLPLUS $2 -S -L -R 3 ${DBRWUSER}/${DBRWPW}@${DBNAME}`
	RE=$?
	echo "$RC"
	if [ $RE -eq 0 ]; then
		echo "$RC" | $EGREP -qi "error"
		if [ $? -eq 0 ]; then RE=1; fi
	fi
	if [ $RE -eq 0 ]; then
		echo "$RC" | $EGREP -q "ORA-[0-9]"
		if [ $? -eq 0 ]; then RE=1; fi
	fi
	return $RE
}

# input: sql query, optional sqlplus command-line params
oracle_ro_query() {
	# if password not yet queried, query it now
	prompt_oracle_pw ro
	if [ -z "$KAMAILIO_ORASEL" ]; then
		mdbg "oracle_ro_query: $SQLPLUS $2 -S -L -R 3 $DBROUSER@$DBNAME '$1'"
		RC=`echo "$SESSOPT $1" | $SQLPLUS $2 -S -L -R 3 ${DBROUSER}/${DBROPW}@${DBNAME}`
		RE=$?
		echo "$RC"
		if [ $RE -eq 0 ]; then
			echo "$RC" | $EGREP -qi "error"
			if [ $? -eq 0 ]; then RE=1; fi
		fi
		if [ $RE -eq 0 ]; then
			echo "$RC" | $EGREP -q "ORA-[0-9]"
			if [ $? -eq 0 ]; then RE=1; fi
		fi
		return $RE
	else
		mdbg "oracle_ro_query: $KAMAILIO_ORASEL $DBROUSER@$DBNAME $2 -N -e '$1'"
		$KAMAILIO_ORASEL ${DBROUSER}/${DBROPW}@${DBNAME} $2 -Ne "$1"
		return $?
	fi
}

DBCMD=oracle_query
DBROCMD=oracle_ro_query
DBRAWPARAMS=""
if [ -n "$KAMAILIO_ORASEL" ]; then
DBRAWPARAMS="-B"
fi
