#!/bin/bash

sid=`echo $ORACLE_SID`

if [ "$sid" = "" ]; then
   echo "No ORACLE_SID set in this environment"
   exit
fi

ohome=`echo $ORACLE_HOME`

if [ "$ohome" = "" ]; then
   echo "No ORACLE_HOME set in this environment"
   exit
fi

sqlplus -s  /nolog << EOF
conn sys/oradba as sysdba

host echo "Shutting the DB down..."
SHUTDOWN IMMEDIATE;
host echo "Starting the DB in restrict mode..."
STARTUP RESTRICT;

host echo "Excuting different SYSMAN procsdures..."
EXEC sysman.emd_maintenance.remove_em_dbms_jobs;
EXEC sysman.setEMUserContext('',5);
REVOKE dba FROM sysman;
  
DECLARE
      CURSOR c1 IS
      SELECT owner, synonym_name name
      FROM dba_synonyms
      WHERE table_owner = 'SYSMAN';

      BEGIN
      FOR r1 IN c1 LOOP
      IF r1.owner = 'PUBLIC' THEN
 
      EXECUTE IMMEDIATE 'DROP PUBLIC SYNONYM '||r1.name;
      ELSE
      EXECUTE IMMEDIATE 'DROP SYNONYM '||r1.owner||'.'||r1.name;
 
     END IF;
      END LOOP;
 END;
/
 
DROP USER mgmt_view CASCADE;
DROP ROLE mgmt_user;
host echo "Dropping SYSMAN schema - this may take a while..."
DROP USER sysman CASCADE;
host echo "Disabling restricted mode"
ALTER SYSTEM DISABLE RESTRICTED SESSION;

EOF

cd $ORACLE_HOME/dbs
#rm -f orapw$sid
#orapwd file=$ORACLE_HOME/dbs/orapw$sid password=oradba entries=5

#sqlplus -s  /nolog << EOF

#connect SYS/oradba as SYSDBA
#set echo off
#set pause off
#spool /exlibris/app/oracle/admin/$ORACLE_SID/scripts/emRepository.log
#@$ORACLE_HOME/sysman/admin/emdrep/sql/emreposcre $ORACLE_HOME SYSMAN oradba TEMP ON;
#WHENEVER SQLERROR CONTINUE;
#spool off

#EOF

echo "Creating Oracle EM dbconsole..."

$ORACLE_HOME/bin/emca -config dbcontrol db -repos create -silent -PORT 1521 -SERVICE_NAME $ORACLE_SID -SYS_PWD oradba -SID $ORACLE_SID -DBSNMP_PWD  oradba  -SYSMAN_PWD oradba -DBCONTROL_HTTP_PORT 1158 -AGENT_PORT 3938 -RMI_PORT 5521 -JMS_PORT 5541

$ORACLE_HOME/bin/emctl start dbconsole

