#!/bin/bash
########################################################################
#
# Execute SQL querys and get DB configuration data from vhcs2.conf
#
# Author: Carsten Schoene
# Last change: 04.01.2006
#
########################################################################
#
# check if config exists
if [ -f /etc/vhcs2/vhcs2.conf ] ; then


for a in `cat /etc/vhcs2/vhcs2.conf | grep ^DATABASE | sed -e s@" "@""@g`
do
	export $a
done


# use vhcs2 function to decrypt password from config
if [ -f /etc/redhat-release ] ; then
PHPCODE="
<?php
include('/var/www/vhcs2/gui/include/vhcs2-db-keys.php');
include('/var/www/vhcs2/gui/include/vhcs-config.php');
echo decrypt_db_password(\"$DATABASE_PASSWORD\");
?>
"
else
PHPCODE="
<?php
include('/srv/www/vhcs2/gui/include/vhcs2-db-keys.php');
include('/srv/www/vhcs2/gui/include/vhcs-config.php');
echo decrypt_db_password(\"$DATABASE_PASSWORD\");
?>
"
fi

# we only decrypt non-empty passwords
if [ "${DATABASE_PASSWORD}" != "" ] ; then
# overwrite variable with decrypted value
DATABASE_PASSWORD=`echo -e ${PHPCODE} | php`
fi

if [ $# -gt 1 ] ; then
	if [ "$1" == "-f" ] ; then
		if [ -f "$2" ] ; then
			FILE=$2
			APPEND="< ${FILE}"
		else
			echo "file: $2 not found"
			exit 1
		fi
	else
		echo "invalid command line syntax:"
		echo "Usage: $0 <QUERY | -f FILE>"
		exit 1
	fi
else
	QUERY=$1
	APPEND="-e \"${QUERY}\""
fi

if [ -n "${DATABASE_USER}" ] && [ -n "${DATABASE_PASSWORD}" -o "${DATABASE_PASSWORD}" == "" ] && [ -n "${DATABASE_HOST}" ] && [ -n "${DATABASE_NAME}" ] && [ -n "${APPEND}" ] ; then

	# run the sql query
	if [ "${DATABASE_PASSWORD}" == "" ] ; then
		echo	mysql --skip-column-names -u ${DATABASE_USER} -h ${DATABASE_HOST} ${DATABASE_NAME} "${APPEND}" | sh
	else
		echo	mysql --skip-column-names -u ${DATABASE_USER} -p${DATABASE_PASSWORD} -h ${DATABASE_HOST} ${DATABASE_NAME} "${APPEND}" | sh
	fi

else
	echo "Can't import correct database settings from vhcs2.conf!"
	echo "Database specific update failed!"
	exit 1
fi

fi # endif config exists
exit 0
