#!/bin/sh
#
set -x
which awk
# Script to create oracle database

if [ $# -ne 1 ]
then
	echo "Usage: createdb.sh <database dir>"
	exit 1
fi

if [ "$ORACLE_HOME" = "" ]
then
	echo "$ORACLE_HOME"
	echo "You must set the ORACLE_HOME environment variable"
	exit 1
fi

if [ "$ORACLE_SID" = "" ]
then
	echo "$ORACLE_SID"
	echo "You must set the ORACLE_SID environment variable"
	exit 1
fi

####################
# Set the database and database directory vars
#####################
DB=${ORACLE_SID}
DB_DIR=$1
###################################################
# If the database already exists warn that we will 
# destroy it.
####################################################
### if [ -f "$ORACLE_HOME"/dbs/init${DB}.ora  ]
### then
### 	echo  "$ORACLE_HOME"/dbs/init${DB}.ora
### 	echo "Database already exists. Ok to destroy y/n ? \c"
### 	read junk
### 	if [ "$junk" != 'y' -a "$junk" != 'Y' ]
### 	then
### 		echo  "database create cancelled"
### 		exit 1
### 	fi
### fi

####################################
# Check to see that the target database directory
# exists and has write permission.
####################################
if [ ! -d "$DB_DIR" ] 
then
	echo "$DB_DIR does not exist. Please create it first."
	exit 1
fi


########################################################
# Go and run the create_init.sh script
# to build the correct pfiles and .ora files for Oracle 
########################################################
#echo "Creating the \$ORACLE_HOME/dbs .ora files ..."
#create_init.sh $DB $DB_DIR
#cp init${ORACLE_SID}.ora $ORACLE_HOME/dbs/.

SYS=${DB_DIR}/sys_${DB}
SYS_AUX=${DB_DIR}/sysaux_${DB}

LOG1=${DB_DIR}/log1.f
LOG2=${DB_DIR}/log2.f
LOGSZ="900000M"

TEMP=${DB_DIR}/temp_${DB}
STATS=${DB_DIR}/stats_${DB}

UNDO=${DB_DIR}/undo_${DB}
# Create database

sqlplus <<EOT
CONNECT / as sysdba
shutdown;
startup nomount

CREATE DATABASE $DB
CONTROLFILE REUSE
LOGFILE GROUP 1 '${LOG1}' SIZE ${LOGSZ} REUSE,
        GROUP 2 '${LOG2}' SIZE ${LOGSZ} REUSE
MAXDATAFILES 100
DATAFILE '${SYS}' size 3072M REUSE
SYSAUX DATAFILE '${SYS_AUX}' size 8100M REUSE
BIGFILE DEFAULT TEMPORARY TABLESPACE temp_ts
    TEMPFILE '${TEMP}' SIZE 80000M REUSE
BIGFILE UNDO TABLESPACE undo_ts DATAFILE '${UNDO}'  SIZE 400000M REUSE
    BLOCKSIZE 8k;

exit
EOT


echo "Running catalog scripts ..."
sqlplus <<EOT
CONNECT / as sysdba
@?/rdbms/admin/catalog;
@?/rdbms/admin/catldr.sql
@?/rdbms/admin/catproc.sql
EXIT
EOT

echo "Catalog done."

sqlplus <<EOT
CONNECT / as sysdba
CREATE USER spec IDENTIFIED BY spec;
GRANT CONNECT, RESOURCE TO spec;
GRANT ALL PRIVILEGES TO spec IDENTIFIED BY spec;

CREATE BIGFILE TABLESPACE stats_ts
        DATAFILE '${STATS}' SIZE 10000M REUSE
        EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;

ALTER USER spec
	TEMPORARY TABLESPACE temp_ts;

EXIT

EOT

#./schema.sh $ORACLE_HOME/dbs

