#!/bin/sh
#
# cgmkdb
# ------
# Utility script to generate an empty cego database with one tableset.
#
# (C)opyright 2010,2011,2012.2013 by Bjoern Lemke
#
# The database and tableset parameters defined below
# should be edited and customized to appropriate values.
#
# Thanks to Keve Nagy, this script has been expanded and improved very much
#

## Variable definitions:
PROGVERSION="2.4";    ## Helps to identify and keep track of different editions.
DEFCEGOROOT=/usr/local/cego
DEFAPPSIZE=3000

## Function definitions:
printVersion() {
  echo "cgmkdb version ${PROGVERSION} - The cego database generator utility."
}

printUsage() {
  echo "Usage : $0 [-r <root_path>] [-t <tableset_name>] [-u <ts_username>] [ -s <appsize> ] <db_name>"
  echo ""
}

## Parameter handling:
if [ $# -eq 1 ]
then
  case "$1" in
    -h|-\?|-help|--help)  printVersion; printUsage; exit 0;;
    -v|-V|--version)  printVersion; exit 0;;
  esac
fi

args=`getopt r:R:t:T:u:U:s:S: $*`
test $? != 0 && { printUsage; exit 1; }

set -- $args

for i
do
  case "$i" in
    -r|-R)  CEGOROOT=$2; shift; shift;;
    -t|-T)  CEGOTABLESET=$2; shift; shift;;
    -u|-U)  CEGOUSER=$2; shift; shift;;
    -s|-S)  APPSIZE=$2; shift; shift;;
    --)  DBNAME=$2; shift; break;;
  esac
done


test -z "$DBNAME" && { echo "No dbname specified."; printUsage; exit 1; }

## Remove tailing "/" chars from $CEGOROOT
if [ "${CEGOROOT}x" != "x" ]
then
  varLen=${#CEGOROOT}
  pos=`expr ${varLen} - 1`
  tailChar=`echo ${CEGOROOT}|cut -c ${varLen}-${varLen}`
  while test "${tailChar}x" = "/x"
  do
    CEGOROOT=`echo ${CEGOROOT}|cut -c 1-${pos}`
    varLen=${#CEGOROOT}
    pos=`expr ${varLen} - 1`
    tailChar=`echo ${CEGOROOT}|cut -c ${varLen}-${varLen}`
  done
fi

## This is where the new database should be created.
test -z "$CEGOROOT" && CEGOROOT=$DEFCEGOROOT
test ! -d $CEGOROOT && { echo "Database root directory $CEGOROOT must exist."; exit 1; }

echo "Database name: $DBNAME"
CEGO=`which cego`;               ## path to the cego executable
DBROOT=${CEGOROOT}
DBXML=${DBROOT}/${DBNAME}.xml;   ## name of the database xml file
LOGFILE=${DBROOT}/${DBNAME}.log
LOCKFILE=${DBROOT}/${DBNAME}.lock
MAINARGS="--dbxml=${DBXML} --logfile=${LOGFILE} --lockfile=${LOCKFILE}"

if [ -f $DBXML ]
then
    echo "Detected existing database configuration file ${DBXML}"
    echo "Tableset will be just added to it."

    /bin/echo "Please note : Additional tableset still has to be added manually to the existing startup script"
    
    TS=${CEGOTABLESET}
    TSROOT=${DBROOT}/${DBNAME}_data
    
else

    echo "Creating database in directory $DBROOT ..."
    
##
## Database parameters:
    PAGESIZE=8192
    HOSTNAME=`hostname`
    ADMPORT=2000
    DBPORT=2200
    LOGPORT=3000
    PIDFILE=${DBROOT}/${DBNAME}.pid
    ADMINUSER=cgadm
    ADMINPWD=cgadm
# DEBUGLEVEL=DEBUG
    DEBUGLEVEL=NOTICE
    DBSTARTSCRIPT=${DBROOT}/${DBNAME}_start
    DBSTOPSCRIPT=${DBROOT}/${DBNAME}_stop
##
    TS=${CEGOTABLESET:-$DBNAME}
    TSROOT=${DBROOT}/${DBNAME}_data

    DBUSER=${CEGOUSER:-$DBNAME}

    TSAPPSIZE=${APPSIZE:-$DEFAPPSIZE}
    
    DBPWD=${DBUSER}
    
##########################
### end of customizing ###
##########################

    # mkdir ${DBROOT}
    # test $? != 0 && { echo "Cannot create database directory."; exit 1; }

    /bin/echo -n " * Generating database configuration xml ... "
    ${CEGO} --mode=init --dbname=${DBNAME} --hostname=${HOSTNAME} --pgsize=${PAGESIZE} --dbport=${DBPORT} --admport=${ADMPORT} --logport=${LOGPORT} --pidfile=${PIDFILE} --loglevel=${DEBUGLEVEL} ${MAINARGS}
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }
    
    /bin/echo -n " * Creating admin user for the database ... "
    ${CEGO} --mode=adduser --user=${ADMINUSER}/${ADMINPWD} --role=admin ${MAINARGS}
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }
    
    /bin/echo -n " * Creating role ALL ... "
    ${CEGO} --mode=addrole --role=ALL ${MAINARGS} 
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }
    
    /bin/echo -n "   + Creating role permission ... "
    ${CEGO} --mode=addperm --permid=${TS}_P --role=ALL --tableset=${TS} --filter="ALL" --perm="ALL"  ${MAINARGS} 
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }
    
    /bin/echo -n "   + Creating user:${DBUSER} ... "
    ${CEGO} --mode=adduser --user=${DBUSER}/${DBPWD} --role=ALL ${MAINARGS}
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }


    mkdir ${TSROOT}
    test $? != 0 && { echo "Cannot create tableset root directory."; exit 1; }


    /bin/echo -n " * Creating database start script ... "
    cat << _EOF_ > ${DBSTARTSCRIPT}
#!/bin/sh
echo "Starting cego database-instance:${DBNAME} with tableset:${TS} ..."
cego --mode=daemon ${MAINARGS} --tableset=${TS} --pidfile=${PIDFILE} --protocol=serial
sleep 2
echo ""
_EOF_
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }
    chmod 755 ${DBSTARTSCRIPT}
    
    /bin/echo -n " * Creating database stop script ... "
    cat << _EOF_ > ${DBSTOPSCRIPT}
#!/bin/sh
echo "Stopping cego database-instance:${DBNAME} with tableset:${TS} ..."
myPID=\`cat ${PIDFILE}\`
/bin/echo -n " * Signaling PID:\${myPID} ... "
kill -INT \${myPID} || { echo "Failed to signal PID:\${myPID}."; exit 1; }
echo "Done."
echo " * Waiting for lockfile to clear ..."
echo '   This takes a few seconds. Please be patient!'
myTimeout=1;
while test -e ${LOCKFILE}
do
  test \${myTimeout} -ge 60 && { echo "Timeout reached. Exiting."; echo "Please check for existing cego daemon."; exit 1; }
  sleep 1
  myTimeout=\`expr \${myTimeout} + 1\`;
done
echo "   Lockfile cleared in \${myTimeout} seconds."
/bin/echo -n " * Housekeeping ... "
test -e ${PIDFILE} && rm ${PIDFILE}
test \$? -eq 0 && echo "Done." || { echo FAILED; exit 1; }
echo "Database shutdown complete." 
echo ""
_EOF_
    test $? -eq 0 && echo OK || { echo FAILED; exit 1; }
    chmod 755 ${DBSTOPSCRIPT}
    echo "Done."
    echo ""
    
fi

## Tableset defs:

# TSROOT=${DBROOT}/${DBNAME}_data
TSTICKET=${TSROOT}/tsticket.xml
SYSSIZE=100
TMPSIZE=3000
LOGFILESIZE=1000000
LOGFILENUM=3
SORTAREASIZE=10000000
# APPSIZE=3000

/bin/echo " * Creating a tableset ... "
/bin/echo -n "   + Defining tableset:${TS} ... "
${CEGO} --mode=define ${MAINARGS} --tableset=${TS} --tsdef="tsroot:${TSROOT},tsticket:${TSTICKET},syssize:${SYSSIZE},tmpsize:${TMPSIZE},logfilesize:${LOGFILESIZE},logfilenum:${LOGFILENUM},appsize:${TSAPPSIZE},sortareasize=${SORTAREASIZE}"
test $? -eq 0 && echo OK || { echo FAILED; exit 1; }

/bin/echo -n "   + Finalizing tableset:$TS ... "
${CEGO} --mode=create ${MAINARGS} --tableset=${TS}
test $? -eq 0 && echo OK || { echo FAILED; exit 1; }

