#!/bin/sh
#
# cgmkdb
# ------
# Utility script to generate an empty cego database with one tableset.
#
# (C)opyright 2010,2011,2012 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

## 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>] <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: $*`
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;;
    --)  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}/${DBNAME}
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 [ -d $DBROOT ]
then
    echo "Detected existing database directory $DBROOT/$DBNAME."
    echo "Tableset will be just added to it."

    TS=${CEGOTABLESET}
    TSROOT=${DBROOT}/data
    
else

    echo "Creating database in directory $DBROOT ..."
    
##
## Database parameters:
    PAGESIZE=16384
    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}/data

    DBUSER=${CEGOUSER:-$DBNAME}
    DBPWD=${DBUSER}
##########################
### end of customizing ###
##########################

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

    # we do not need to generate database xml file maually, rather use the init mode of cego

# cat << _EOF_ > $DBXML
# <?xml version="1.0" ?>
# <!DOCTYPE CEGO_DB_SPEC>
# <DATABASE NAME="$DBNAME" PAGESIZE="$PAGESIZE" HOSTNAME="$HOSTNAME" ADMINPORT="$ADMPORT" LOGPORT="$LOGPORT" DATAPORT="$DBPORT" PIDFILE="$PIDFILE# " MAXFID="1" MAXTSID="1" NUMRECSEMA="2141" NUMSYSPAGESEMA="2141" NUMDATAPAGESEMA="2141" NUMIDXPAGESEMA="2141" NUMRBPAGESEMA="2141" NUMDATAFILES# EMA="1013" NUMBUFFERPOOLSEMA="1013" MAXFIXTRIES="30" CSMODE="ON" QESCMODE="ON" LOGMNGPROG="./cglogmng">
#	<MODULE NAME="ALL" LEVEL="$DEBUGLEVEL"></MODULE>
# </DATABASE> 
# _EOF_
# test $? -eq 0 && echo OK || { echo FAILED; 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} ..."
nohup cego --mode=daemon ${MAINARGS} --pidfile=${PIDFILE} &
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 "This is NOT good."; 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}/data
TSTICKET=${TSROOT}/tsticket.xml
SYSSIZE=100
TMPSIZE=3000
LOGFILESIZE=1000000
LOGFILENUM=3
SORTAREASIZE=10000000
APPFILE=${TSROOT}/${TS}_data01.dbf
APPSIZE=3000

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

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