#!/bin/bash

E_BADARGS=65
EXPECTED_ARGS=1
CONFDIR=/var/opi/etc

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: $0 config"
  exit $E_BADARGS
fi

if [ -e "$CONFDIR/$1.conf" ]
then
. $CONFDIR/$1.conf
else
  echo "Missing configuration"
  exit $E_BADARGS
fi

if [ -z ${_DBC_DBNAME_+x} ]
then
  echo "Missing dbname"
  exit $E_BADARGS
fi

if [ -z ${_DBC_DBUSER_+x} ]
then
  echo "Missing dbuser"
  exit $E_BADARGS
fi

if [ -z ${_DBC_DBPASS_+x} ]
then
  echo "Missing db password"
  exit $E_BADARGS
fi


MYSQL=`which mysql`
 
Q1="CREATE DATABASE IF NOT EXISTS $_DBC_DBNAME_;"
Q2="GRANT ALL ON $_DBC_DBNAME_.* TO '$_DBC_DBUSER_'@'localhost' IDENTIFIED BY '$_DBC_DBPASS_';"
Q3="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}"

$MYSQL -uroot -e "$SQL"
