#!/usr/bin/sh
# Copyright 08/06/99 Sun Microsystems, Inc. All Rights Reserved.
# "@(#)em_db_create	1.49 99/08/06 Sun Microsystems"
#

###############################################################################
# em_db_create
###############################################################################
#
# Create the database.  
#
# Usage: 
#
#	em_db_create -d			Create the server and database.
#	em_db_create -t			Create the tables.
#	em_db_create -s			Create the seed table only.
#
###############################################################################


###############################################################################
# errmsg  
###############################################################################
#
# Echo the arguments.
#
###############################################################################

errmsg()
{
    if [ "$1" = "-n" ] ; then
	shift
	gettext em_db_create "$*"		# no newline
    else
	gettext em_db_create "$*\\n"
    fi
}


###############################################################################
# Environment
###############################################################################
#
# Set up the environment.
#
###############################################################################

trap 'errmsg "\\nem_db_create interrupted."; exit 1' 1 2 3 15

EM_DB_HOME=${INFORMIXDIR:-/opt/SUNWemrdb}
INFORMIXDIR=$EM_DB_HOME

HOSTNAME=`$EM_HOME/bin/get_local_host | /bin/sed -e 's/-/_/g'`
EM_DB_SERVER=${INFORMIXSERVER:-${HOSTNAME}_emdb}
INFORMIXSERVER=$EM_DB_SERVER

EM_DB_NAME=${EM_DB_NAME:-emdb}
EM_MISDB_NAME=${EM_MISDB_NAME:-emmisdb}
ONCONFIG=onconfig.em

export EM_DB_HOME EM_DB_NAME EM_MISDB_NAME INFORMIXDIR INFORMIXSERVER ONCONFIG

PATH=$EM_DB_HOME/bin:/bin:/usr/bin:/usr/ucb:$PATH:
LD_LIBRARY_PATH=$EM_DB_HOME/lib:$EM_DB_HOME/lib/esql:/usr/openwin/lib:$LD_LIBRARY_PATH
SHLIB_PATH=$LD_LIBRARY_PATH

export PATH LD_LIBRARY_PATH SHLIB_PATH

###############################################################################
# debugmsg  
###############################################################################
#
# Echo the arguments only if the -d option hasn't been given. 
#
###############################################################################

debugmsg() 
{
    gettext em_db_create "$*\\n" > ${debug_device:-/dev/tty} 2>&1
}



###############################################################################
# progress
###############################################################################
#
# Mark the passage of time to convince the user we haven't really hung at all.
#
###############################################################################

progress()
{
    # marker for monitor
    cp /dev/null /tmp/emha_progress > /dev/null 2>&1

    if [ "${quiet:-FALSE}" = TRUE -o "${debug:-FALSE}" = TRUE ] ; then
	return
    fi

    progress_counter=`expr ${progress_counter:-1} + 1`   
    position=`expr $progress_counter % 4`

    if [ $position -eq 0 ] ; then
	echo '|\b\c'
    elif [ $position -eq 1 ] ; then
	echo '/\b\c'
    elif [ $position -eq 2 ] ; then
	echo '-\b\c'
    else
	echo '\\\b\c'
    fi
}


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

create_rdb()
{
    #
    # create a 21mb dbspace for the physical log
    #

    debugmsg 'Creating physical log dbspace...'
    progress
    onspaces -c -d pldbs -p $EM_RUNTIME/data/db/pldbs1 -o 0 -s 21000 \
	     > ${debug_device:-/dev/null} 2>&1

    #
    # create a 26mb dbspace for the logical log
    #

    debugmsg 'Creating logical log dbspace...'
    progress
    onspaces -c -d lldbs -p $EM_RUNTIME/data/db/lldbs1 -o 0 -s 26000 \
	     > ${debug_device:-/dev/null} 2>&1

    #
    # create a 40mb dbspace for the MIS tables 
    #

    debugmsg 'Creating MIS database space...'
    progress
    onspaces -c -d emmisdbs -p $EM_RUNTIME/data/db/emmisdbs1 \
             -o 0 -s 40000 > ${debug_device:-/dev/null} 2>&1

    #
    #
    # create a 40mb dbspace for the topology tables
    #

    debugmsg 'Creating topology database space...'
    progress
    onspaces -c -d emdbs -p $EM_RUNTIME/data/db/emdbs1 \
             -o 0 -s 40000 > ${debug_device:-/dev/null} 2>&1

    #
    # add 5 logical log files of 5mb each.
    #

    debugmsg 'Adding logical log files...'
    progress
    onparams -a -d lldbs -s 5000 > ${debug_device:-/dev/null} 2>&1
    progress
    onparams -a -d lldbs -s 5000 > ${debug_device:-/dev/null} 2>&1
    progress
    onparams -a -d lldbs -s 5000 > ${debug_device:-/dev/null} 2>&1
    progress
    onparams -a -d lldbs -s 5000 > ${debug_device:-/dev/null} 2>&1
    progress
    onparams -a -d lldbs -s 5000 > ${debug_device:-/dev/null} 2>&1

    #
    # make the new logical logs available by doing a level 0 backup
    #

    debugmsg 'Making new logical logs available...'
    progress
    ontape -s -L 0 > ${debug_device:-/dev/null} 2>&1

    #
    # switch the logical log files to start with a newly added logical log.
    # this step is necessary so we can remove the default logical logs.
    # jump 3 logical logs (the defaults)
    #

    debugmsg 'Switching logical log files...'
    progress
    onmode -l > ${debug_device:-/dev/null} 2>&1
    progress
    onmode -l > ${debug_device:-/dev/null} 2>&1
    progress
    onmode -l > ${debug_device:-/dev/null} 2>&1

    #
    # make the first new logical log the one being used 
    #

    progress
    ontape -s -L 0 > ${debug_device:-/dev/null} 2>&1

    #
    # drop the default logical logs
    #

    debugmsg 'Dropping default logical logs...'
    progress
    onparams -d -l 1 -y > ${debug_device:-/dev/null} 2>&1
    progress
    onparams -d -l 2 -y > ${debug_device:-/dev/null} 2>&1
    progress
    onparams -d -l 3 -y > ${debug_device:-/dev/null} 2>&1

    #
    # modify the physical log to use the pldbs and make it 20mb.
    #

    debugmsg 'Modifying physical log to use new file...'
    progress
    onparams -p -s 20000 -d pldbs -y > ${debug_device:-/dev/null} 2>&1

    #
    # bring the instance to online mode
    #

    debugmsg 'Database server going multi-user...'
    progress
    onmode -m 

    #
    # The creation returns pretty quickly, but the server stays in 
    # single-user mode until initialization is complete.  Wait for the 
    # server to leave single-user mode.
    #

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

	if [ $? -eq 0 ] ; then
 		while true; do
 
             grep "\'sysmaster\' database built successfully" $EM_RUNTIME/debug/database.log > ${debug_device:-/dev/null} 2>&1
             if [ $? -eq 0 ] ; then
 				grep "\'sysutils\' database built successfully" $EM_RUNTIME/debug/database.log > ${debug_device:-/dev/null} 2>&1
 				if [ $? -eq 0 ] ; then
                     break
 				else
                     continue
 				fi
             else
                 continue
             fi
 
 		done

	    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

    #
    # Create database. 
    #

    dbaccess - - > ${debug_device:-/dev/null} 2>&1 <<- EOF
	create database $EM_MISDB_NAME in emmisdbs with log;
	create database $EM_DB_NAME in emdbs with buffered log;
	EOF
    progress

}



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

create_tables()
{
    #
    # MIS tables
    #
    dbaccess $EM_MISDB_NAME - > ${debug_device:-/dev/null} 2>&1 <<- EOF
	grant DBA to emsuusr;
	create table ptable          
	    (keyhashed integer, blob byte in table) 
	    lock mode row;
	create index ptable_idx on ptable(keyhashed);
	revoke all on ptable from public;

	create table pdata           
	    (keyhashed integer, blob byte in table) 
	    lock mode row;
	create index pdata_idx on pdata(keyhashed);
	revoke all on pdata from public;

	create table pcounter           
	    (keyhashed integer, blob byte in table) 
	    lock mode row;
	create index pcounter_idx on pcounter(keyhashed);
	revoke all on pcounter from public;

	create table fdn_table 
	    (keyhashed integer, blob byte in table)
	    lock mode row;
	create index fdn_table_idx on fdn_table(keyhashed);
	revoke all on fdn_table from public;

	create table em_object       
	    (keyhashed integer, blob byte in table) 
	    extent size 64 next size 64
	    lock mode row;
	create index em_object_idx on em_object(keyhashed);
	revoke all on em_object from public;

	create table em_objectvalues 
	    (keyhashed integer, blob byte in table) 
	    extent size 64 next size 64
	    lock mode row;
	create index em_objectvalue_idx on em_objectvalues(keyhashed);
	revoke all on em_objectvalues from public;

	create table em_child        
	    (keyhashed integer, blob byte in table) 
	    extent size 1000 next size 500
	    lock mode row;
	create index em_child_idx on em_child(keyhashed);
	revoke all on em_child from public;

	create table em_children     
	    (keyhashed integer, blob byte in table) 
	    extent size 1000 next size 500
	    lock mode row;
	create index em_children_idx on em_children(keyhashed);
	revoke all on em_children from public;

	create table operator_actions
	    (logfdn  		char(1000),
	     logrecordid 	integer, 
	     operatorname 	varchar(16), 
	     actionname 	varchar(30), 
	     actiontime 	date, 
	     attributename 	varchar(20),
	     oldattributevalue  varchar(255),
	     newattributevalue  varchar(255));

	revoke all on operator_actions from public;
	grant insert on operator_actions to public;

	EOF

    #
    # Topology tables
    #
    dbaccess $EM_DB_NAME - > ${debug_device:-/dev/null} 2>&1 <<- EOF2
	grant DBA to emsuusr;
	CREATE TABLE topo_type(
        	id                      INTEGER
                                	PRIMARY KEY,
        	type_name               VARCHAR(255)
                                	NOT NULL,
        	default_layer           VARCHAR(255)
                                	NOT NULL,
        	max_topo_level          SMALLINT
                                	DEFAULT 0,
        	max_visible_level       SMALLINT
                                	DEFAULT 0,
        	draw_method             SMALLINT
                                	DEFAULT 0
                                	CHECK (draw_method BETWEEN 0 AND 9)
	);
	REVOKE ALL ON topo_type FROM PUBLIC;

	CREATE TABLE topo_node(
        	id              INTEGER
                        	PRIMARY KEY,
        	state           INTEGER
                        	DEFAULT 0,
        	propagate_up    INTEGER
                        	DEFAULT 1
                        	CHECK (propagate_up BETWEEN 0 AND 1),
        	name            VARCHAR(255),
        	type_id         INTEGER
                        	REFERENCES topo_type (id),
        	layer           VARCHAR(255)
                        	DEFAULT '',
        	is_view         INTEGER 
                        	NOT NULL
                        	CHECK (is_view BETWEEN 0 AND 1)
	)
        EXTENT SIZE 2000
        NEXT SIZE   1000;
	REVOKE ALL ON topo_node FROM PUBLIC;
	
	CREATE TABLE family(
        	parent          INTEGER
                        	REFERENCES topo_node (id),
        	child           INTEGER
                        	REFERENCES topo_node (id),
        	x               INTEGER
                        	NOT NULL,
        	y               INTEGER
                        	NOT NULL,
        	z               INTEGER
                        	NOT NULL
	)
        EXTENT SIZE 1200
        NEXT SIZE   600;
	REVOKE ALL ON family FROM PUBLIC;
        CREATE INDEX child_idx ON family(child);

	CREATE TABLE peers(
        	id              INTEGER 
                        	REFERENCES topo_node (id),
        	peer            INTEGER
                        	REFERENCES topo_node (id)
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON peers FROM PUBLIC;
	
	CREATE TABLE propagate_peers(
        	id              INTEGER 
                        	REFERENCES topo_node (id),
        	peer            INTEGER
                        	REFERENCES topo_node (id)
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON propagate_peers FROM PUBLIC;
	CREATE INDEX peer_idx ON propagate_peers(peer);
	
	CREATE TABLE alarm_info(
        	id              INTEGER
                        	UNIQUE
                        	REFERENCES topo_node (id),
        	critical        INTEGER
                        	DEFAULT 0
                        	CHECK (critical >= 0),
        	major           INTEGER
                        	DEFAULT 0
                        	CHECK (major >= 0),
        	minor           INTEGER
                        	DEFAULT 0
                       		CHECK (minor >= 0),
        	warning         INTEGER
                        	DEFAULT 0
                        	CHECK (warning >= 0),
        	indeterminate   INTEGER
                        	DEFAULT 0
        	                CHECK (indeterminate >= 0),
        	prop_severity   INTEGER
                        	DEFAULT 5
                        	CHECK (prop_severity BETWEEN 0 AND 5)
	)
        EXTENT SIZE 1200
        NEXT SIZE   600;
	REVOKE ALL ON alarm_info FROM PUBLIC;
		
	CREATE TABLE managed_objs(
        	id              INTEGER
                        	REFERENCES topo_node (id),
        	mo_id           INTEGER
	)
        EXTENT SIZE 1000
        NEXT SIZE   500;
	REVOKE ALL ON managed_objs FROM PUBLIC;
	CREATE INDEX moiid_idx ON managed_objs(mo_id);
	
	CREATE TABLE array_info(
        	id              INTEGER
                        	UNIQUE
                        	REFERENCES topo_node (id),
        	width           INTEGER
                        	DEFAULT 0,
        	height          INTEGER
                        	DEFAULT 25,
        	num_columns     INTEGER
                        	DEFAULT 0,
        	orientation     INTEGER
                        	DEFAULT 0
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON array_info FROM PUBLIC;
	
	CREATE TABLE array_visible(
        	id              INTEGER
                        	REFERENCES array_info (id),
        	visible_child   INTEGER
                        	REFERENCES topo_node (id)
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON array_visible FROM PUBLIC;
	
	CREATE TABLE bus_info(
        	id              INTEGER
                        	REFERENCES topo_node (id),
        	x               INTEGER
                        	NOT NULL,
        	y               INTEGER
                        	NOT NULL,
        	z               INTEGER
                        	DEFAULT 0
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON bus_info FROM PUBLIC;
	
	CREATE TABLE display_status(
        	id              INTEGER
                        	REFERENCES topo_node (id),
        	status          VARCHAR(255)
                        	NOT NULL,
        	value           INTEGER
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON display_status FROM PUBLIC;
	
	CREATE TABLE geo_location(
        	id              INTEGER
                        	UNIQUE
                        	REFERENCES topo_node (id),
        	latitude        REAL
                        	NOT NULL,
        	longitude       REAL
                        	NOT NULL
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON geo_location FROM PUBLIC;
	
	CREATE TABLE monitor(
        	id              INTEGER
                        	UNIQUE
                        	REFERENCES topo_node (id),
        	rotation        INTEGER
                        	NOT NULL
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON monitor FROM PUBLIC;
	
	CREATE TABLE monitor_children(
        	id              INTEGER
                        	REFERENCES monitor (id),
        	child           INTEGER
                        	REFERENCES topo_node (id)
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON monitor_children FROM PUBLIC;
	
	CREATE TABLE node_user_data(
        	id              INTEGER
                        	UNIQUE
                        	REFERENCES topo_node (id),
        	data            BYTE
                        	NOT NULL
	)
        EXTENT SIZE 2400
        NEXT SIZE   1000;
	REVOKE ALL ON node_user_data FROM PUBLIC;
	
	CREATE TABLE topo_view(
        	id              INTEGER
                        	UNIQUE
                        	REFERENCES topo_node (id),
       		background      VARCHAR(255)
                        	DEFAULT '',
        	map_file        VARCHAR(255)
                        	DEFAULT ''
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON topo_view FROM PUBLIC;
	
	CREATE TABLE view_map(
       		id                      INTEGER
                                	UNIQUE
                                	REFERENCES topo_view (id),
        	center_latitude         REAL
                                	NOT NULL,
        	center_longitude        REAL
                                	NOT NULL,
       		width_in_km             REAL
                                	NOT NULL
	)
        EXTENT SIZE 100
        NEXT SIZE   50;
	REVOKE ALL ON view_map FROM PUBLIC;
	
	CREATE TABLE view_cfg_data(
       		id              INTEGER
                               	UNIQUE
                               	REFERENCES topo_view (id),
        	data            BYTE
                        	NOT NULL
	)
        EXTENT SIZE 1000
        NEXT SIZE   500;
	REVOKE ALL ON view_cfg_data FROM PUBLIC;

	CREATE TABLE descendents(
        	id              INTEGER
                        	REFERENCES topo_type (id),
        	descendent      INTEGER
                        	REFERENCES topo_type (id)
	);
	REVOKE ALL ON descendents FROM PUBLIC;
	
	CREATE TABLE ancestors(
        	id              INTEGER
                        	REFERENCES topo_type (id),
        	ancestor        INTEGER
                        	REFERENCES topo_type (id)
	);
	REVOKE ALL ON ancestors FROM PUBLIC;
	
	CREATE TABLE legal_arcs(
        	id              INTEGER
                        	REFERENCES topo_type (id),
        	arc             INTEGER
                        	REFERENCES topo_type (id)
	);
	REVOKE ALL ON legal_arcs FROM PUBLIC;
	
	CREATE TABLE legal_children(
        	id              INTEGER
                        	REFERENCES topo_type (id),
        	child           INTEGER
                        	REFERENCES topo_type (id)
	);
	REVOKE ALL ON legal_children FROM PUBLIC;
	
	CREATE TABLE type_user_data(
        	id              INTEGER
                        	REFERENCES topo_type (id),
        	data            BYTE
                        	NOT NULL
	);
	REVOKE ALL ON type_user_data FROM PUBLIC;
	
	CREATE TABLE topo_node_db(
        	id		INTEGER
                               	PRIMARY KEY,
        	state_prop	SMALLINT
                               	CHECK (state_prop BETWEEN 0 AND 1)
	);
	REVOKE ALL ON topo_node_db FROM PUBLIC;
	
	CREATE TABLE topo_view_db(
        	id		INTEGER
                               	PRIMARY KEY,
        	auto_position	SMALLINT
                               	CHECK (auto_position BETWEEN 0 AND 1)
	);
	REVOKE ALL ON topo_view_db FROM PUBLIC;
	
	CREATE TABLE topo_type_db(
        	id		INTEGER
                               	PRIMARY KEY
	);
	REVOKE ALL ON topo_type_db FROM PUBLIC;
	
	CREATE TABLE db_all_status(
        	id		INTEGER
                        	REFERENCES topo_node_db (id),
        	status          VARCHAR(255)
                        	NOT NULL
	);
	REVOKE ALL ON db_all_status FROM PUBLIC;
	
	CREATE TABLE db_all_layer(
        	id		INTEGER
                        	REFERENCES topo_node_db (id),
        	layer           VARCHAR(255)
                        	NOT NULL
	);
	REVOKE ALL ON db_all_layer FROM PUBLIC;

	CREATE TABLE motable(
        	unique_id       INTEGER 
                        	PRIMARY KEY, 
        	hashval         INTEGER,
        	moi             BYTE IN TABLE
	)
        EXTENT SIZE 5000
        NEXT SIZE   1000;
	REVOKE ALL ON motable FROM PUBLIC;
	CREATE INDEX motable_idx ON motable(hashval);
	GRANT SELECT ON motable TO PUBLIC;
	
	EOF2

	create_seed_table
}

create_seed_table ()
{
    dbaccess $EM_DB_NAME - > ${debug_device:-/dev/null} 2>&1 <<- EOF

	DROP TABLE seedtable;

        CREATE TABLE seedtable (
		seedval		INTEGER, 
		in_use		SMALLINT
		)
	LOCK MODE PAGE;
	GRANT ALL ON seedtable TO PUBLIC;

        INSERT INTO seedtable VALUES (1, 0);
        INSERT INTO seedtable VALUES (2, 0);
        INSERT INTO seedtable VALUES (3, 0);
        INSERT INTO seedtable VALUES (4, 0);

	EOF
}


###############################################################################
# main
###############################################################################
#
# The main portion of this script.
#
###############################################################################

if [ ! -x $EM_DB_HOME/bin/dbaccess ]; then 
    errmsg ""
    errmsg "ERROR: Unable to locate database server manager binary (dbaccess) "
    errmsg -n "in directory "
    errmsg -n "$EM_DB_HOME/bin. "
    errmsg "Database not created. "
    errmsg ""
    exit 1
fi

while getopts dst opt ; do
    case $opt in
	d)
	    create_rdb
	    ;;

	s)
	    create_seed_table
	    ;;

	t)
	    create_tables
	    ;;
    esac
done

exit 0
