#!/usr/bin/sh
#Copyright 01/12/99 Sun Microsystems, Inc. All rights reserved.
#pragma ident "@(#)db_services	1.19 99/01/12 Sun Microsystems"
#

###############################################################################
# db_services
###############################################################################
#
# The Informix-specific functions of em_services.
#
###############################################################################

#
# Environment variables required by the database.
#

if [ -z "$EM_DB_HOME" ] ; then
    EM_DB_HOME=/opt/SUNWemrdb
    export EM_DB_HOME
fi

HOSTNAME=`/bin/uname -n | sed -e 's/-/_/g'`

if [ -z "$EM_DB_SERVER" ] ; then
    EM_DB_SERVER=${HOSTNAME}_emdb
    export EM_DB_SERVER
fi

EM_DB_NAME=emdb; 					export EM_DB_NAME
EM_DB_USER_NAME=${EM_DB_USER_NAME:-informix};		export EM_DB_USER_NAME
EM_DB_USER_ID=`/usr/xpg4/bin/id -u $EM_DB_USER_NAME`; 	export EM_DB_USER_ID
INFORMIXDIR=$EM_DB_HOME;        			export INFORMIXDIR
INFORMIXSERVER=$EM_DB_SERVER;   			export INFORMIXSERVER
ONCONFIG=onconfig.em; 					export ONCONFIG

###############################################################################
# run_as_db_user
###############################################################################
#
# Run the given command as $EM_DB_USER_NAME.  su is too stupid.  If you su
# to yourself, it'll still prompt you for a password.
#
###############################################################################

run_as_db_user()
{
    my_id=`/usr/xpg4/bin/id -u`

    if [ $my_id -eq $EM_DB_USER_ID ] ; then
	eval $*
    else
	su $EM_DB_USER_NAME -c "$*"
    fi

    return $?
}


###############################################################################
# database_is_running
###############################################################################
#
# Returns true (0) if the database is running; false (1) otherwise.
#
###############################################################################

database_is_running()
{
    onstat > /dev/null 2>&1
    return $?
}


###############################################################################
# kill_database
###############################################################################
#
# Kill the database server.
#
###############################################################################

kill_database()
{
    debugmsg "Terminating the database server..."

    if [ "$1" = "-ABRT" ] ; then
	run_as_db_user ${EM_HOME}/bin/em_db_abort
    else
	run_as_db_user ${EM_HOME}/bin/em_db_stop
    fi
    
    exit_status=$?

    if database_is_running; then
	errmsg "Database failed to shutdown."
    elif [ $exit_status -eq 0 ] ; then
	debugmsg "Database shutdown."
    else
	debugmsg "Database was not running."
    fi
}


###############################################################################
# start_database
###############################################################################
#
# Start the database server.
#
###############################################################################

start_database()
{
    if database_is_running ; then
	return
    fi

    debugmsg "Starting the database server..."
    run_as_db_user ${EM_HOME}/bin/em_db_start

    if [ $? -eq 0 ] ; then
	debugmsg "Database warm started."
    else
	errmsg "Database failed to start."
    fi
}


###############################################################################
# create_tables
###############################################################################
#
# Create the tables.
#
###############################################################################

create_tables()
{
    run_as_db_user "em_db_create -t"
}


###############################################################################
# update stats - For query optimization
###############################################################################
update_stats()
{
    my_id=`/usr/xpg4/bin/id -u`

    if [ $my_id -eq $EM_DB_USER_ID ] ; then
	$EM_DB_HOME/bin/dbaccess $EM_DB_NAME - > $debug_device 2>&1 <<- EOF
	    UPDATE STATISTICS HIGH;
	EOF
    else
	su $EM_DB_USER_NAME <<- SUEOF
	    $EM_DB_HOME/bin/dbaccess $EM_DB_NAME - > $debug_device 2>&1 <<- EOF
	    	UPDATE STATISTICS HIGH;
		EOF
	SUEOF
    fi
}



###############################################################################
# drop_logs
###############################################################################
#
# Drop all log tables.
#
###############################################################################

drop_logs()
{
    debugmsg "Deleting log tables..."
    run_as_db_user "em_db_drop -l"
    logs_dropped="-dropped"
}


###############################################################################
# drop_nonlogs
###############################################################################
#
# Drop all the tables except for the logs.
#
###############################################################################

drop_nonlogs()
{
    debugmsg "Deleting tables..."
    run_as_db_user "em_db_drop -t"
}


###############################################################################
# create_rdb
###############################################################################
#
# Create database.
#
###############################################################################

create_rdb()
{
    progress

    #
    # Make the EM_RUNTIME directory if it doesn't already exist.
    #

    if [ ! -d $EM_RUNTIME ] ; then
	mkdir -p $EM_RUNTIME/debug
    fi

    #
    # Check diskspace.
    #

    currently_used=`du -ks $EM_RUNTIME | awk '{ print $1 }'`
    df_with_em=`df -k $EM_RUNTIME | tail -1 | awk '{ print $4 }'`
    available=`expr $df_with_em + $currently_used`
    short=`expr $required_diskspace - $available`

    if [ "$short" -gt 0 ] ; then
	errmsg -n "\\nWarning: "
	errmsg -n "$EM_RUNTIME "
	errmsg "does not have enough free disk space for"
	errmsg -n "the database. "
	errmsg -n "$required_diskspace "
	errmsg "KB of free disk space are required."
	errmsg -n "$EM_RUNTIME "
	errmsg -n "has "
	errmsg -n "$available "
	errmsg -n "KB free and is short "
	errmsg "$short KB.\\n"
	ask_confirm "Continue with em_services reload (y/n)?" \
		    "EM not re-initialized."
	echo "\n"
    fi

    #
    # Remove old database if present.
    #

    progress

    if [ -d $EM_RUNTIME/data/db ]; then
	debugmsg -n "Removing previous data..."
	rm -rf $EM_RUNTIME/data/db
	debugmsg ""
    fi

    #
    # Create database server.
    #

    info -n "Creating database for data repository at: "
    info "$EM_RUNTIME/data/db"

    # 
    # Copy starting onconfig file to one which will be used
    #

    cp $EM_MIS_HOME/build/acct/onconfig.em $INFORMIXDIR/etc/$ONCONFIG
    ex - $INFORMIXDIR/etc/$ONCONFIG << EOF > /dev/null
/^#TAPEDEV_INIT/
s/^#TAPEDEV_INIT/TAPEDEV/
w
q
EOF
    progress

    mkdir -p $EM_RUNTIME/data/db
    chown informix $EM_RUNTIME/data/db
    chgrp informix $EM_RUNTIME/data/db
    progress

    touch $EM_RUNTIME/data/db/rootdbs1
    chown informix $EM_RUNTIME/data/db/rootdbs1
    chgrp informix $EM_RUNTIME/data/db/rootdbs1
    progress

    touch $EM_RUNTIME/data/db/pldbs1
    chown informix $EM_RUNTIME/data/db/pldbs1
    chgrp informix $EM_RUNTIME/data/db/pldbs1
    progress

    touch $EM_RUNTIME/data/db/lldbs1
    chown informix $EM_RUNTIME/data/db/lldbs1
    chgrp informix $EM_RUNTIME/data/db/lldbs1
    progress


    touch $EM_RUNTIME/data/db/rootbls1
    chown informix $EM_RUNTIME/data/db/rootbls1
    chgrp informix $EM_RUNTIME/data/db/rootbls1
    progress

    run_as_db_user "oninit -isy"

    #
    # The database starts pretty quickly, but may take a bit before it's
    # really up.  Wait for it to stop recovering.
    #

    while true; do
	progress
	dbstatus=`onstat -k`
	echo $dbstatus | grep 'Quiescent' > ${debug_device:-/dev/null} 2>&1

	if [ $? -eq 0 ] ; then
	    break				# done initializing
	fi

	echo $dbstatus | grep 'not initialized' > ${debug_device:-/dev/null} 2>&1

	if [ $? -eq 0 ] ; then
	    errmsg 'Database failed to initialize.'
	    exit 1				# server died
	fi

	sleep 5
    done

    run_as_db_user "em_db_create -d"

    #
    # Restore the tape device
    #

    ex - $INFORMIXDIR/etc/$ONCONFIG <<- EOF > /dev/null
	/^TAPEDEV/
	s/^TAPEDEV/#TAPEDEV_INIT/
	/^#TAPEDEV_REAL/
	s/^#TAPEDEV_REAL/TAPEDEV/
	w
	q
	EOF
    progress

    #
    # Make sure TAPEDEV device is up (Assume disk for now; Later:handle tape)
    #

    tapedev=`grep '^TAPEDEV' $INFORMIXDIR/etc/$ONCONFIG | awk '{print $2}'| \
	awk -F# '{print $1}'`
    touch $tapedev
    chmod 660 $tapedev
    chown informix $tapedev
    chgrp informix $tapedev
    progress

    #
    # level 0 backup - necessary as we changed TAPE parameters
    #

    echo '\n' | run_as_db_user "ontape -s -L 0" > $debug_device 2>&1
    while [ $? -ne 0 ]; do
	sleep 10
	debugmsg "Trying to execute ontape again"
        echo '\n' | run_as_db_user "ontape -s -L 0" > $debug_device 2>&1
        progress
    done
    progress

    #
    # Re-creating the database from scratch wipes out the historical logs.
    #

    logs_dropped="-dropped"
}


###############################################################################
# check_runtime
###############################################################################
#
# Check to make sure the runtime environment is properly initialized.  If it's
# not, initialize it.
#
###############################################################################

check_runtime()
{
    mode=$1

    start_database

    if [ $mode = "restart" ] ; then
	em_sql > /tmp/check$$ 2>&1 <<- EOF
	    select tabname from systables where tabname = 'ptable';
	EOF

	grep '0 rows' /tmp/check$$ > $debug_device 2>&1

	if [ $? -eq 0 ] ; then
	    errmsg '\nWarning: The runtime database is missing tables necessary for EM to '
	    errmsg 'run.  Executing "em_services init" to create the tables.\n'
	    mode=start
	fi

	rm -f /tmp/check$$
    fi

    if [ $mode = "start" ] ; then
	debugmsg "Creating tables..."
	create_tables
    fi

    update_stats
}


###############################################################################
# clean_database
###############################################################################
#
# Clean out the database.  The database server is left up and running.
#
###############################################################################

clean_database()
{
    start_database

    if [ $force = TRUE ] ; then
	drop_nonlogs
	drop_logs
    elif [ $quiet = FALSE ] ; then
	drop_nonlogs

	if [ -f $EM_RUNTIME/data/db/rootdbs1 ]; then
	    errmsg -n '\nDo you want to delete the historical log tables (y/n)? '
	    read answer
	
	    if [ "$answer" = "y" ] ; then
		drop_logs
	    else
		info "The historical log tables have been left intact."
	    fi
	fi

    else

	#
	# -q given without -f.  Drop all non-log tables quietly.
	#

	drop_nonlogs
    fi

    drop_dbm				# for safe measure
}


###############################################################################
# force_create
###############################################################################
#
# Force the database creation and init if not already.
#
###############################################################################

force_create()
{
    if [ "$command" != "abort" -a "$command" != "stop" ]; then
	if [ -f $EM_RUNTIME/data/db/rootdbs1 ]; then
	    DBSIZE=`/bin/ls -s $EM_RUNTIME/data/db/rootdbs1 | awk '{print $1}'`
	else
	    DBSIZE=0
        fi

	if [ "$DBSIZE" -lt 1024 -o ! -f $EM_RUNTIME/conf/EM-config ]; then
	    command="reload"
	fi
    fi
}
