# check for root
user=`/bin/id | /usr/bin/grep root | /usr/bin/wc -l`
if [ $user -eq 0 ]; then
        echo "You must be root to execute this script."
        exit 1
fi

ESM_BASE=`/usr/bin/pkgparam SUNWstm ESM_BASE`
if [ $? -ne 0 ]; then
    echo "Could not determine ESM location!"
    exit 1
fi


# helper function to restart database (for making db changes)
start_db () {
    /usr/bin/su - $SSTR_DBOWNER -c ". $SSTR_DBBIN/postgres.env; $SSTR_DBSTART"
    this_try=1
    until /usr/bin/su $SSTR_DBOWNER  -c ". $SSTR_DBBIN/postgres.env; $SSTR_PSQL -l" > /dev/null 2>&1
    do
        if [ $this_try -ge 12 ]; then
            echo "Database still not up - giving up"
            exit 1
        fi
        echo "Wait and try connecting to database again..."
        this_try=`/usr/bin/expr $this_try + 1`
        sleep 10
    done
}


# stop esm and smicc if not running as part of esmpatch
if [ "$ESM_CONTEXT" != "patch" ]; then

    $ESM_BASE/bin/esmcontrol -m stop 

    SMSERVER=/usr/sbin/smcwebserver
    if [ -f "$SMSERVER" ]; then
        $SMSERVER stop
    else
        echo "Unable to stop $SMSERVER"
        exit 1
    fi
fi

# restore changes made to db ddl
SSTR_HOME=$ESM_BASE/sssm
SSTR_DBHOME=$SSTR_HOME/util/pgsql
SSTR_DBBIN=$SSTR_DBHOME/nsm1/bin
SSTR_DBSTART=$SSTR_DBBIN/dbstart.sh
SSTR_DBOWNER=sstr001
SSTR_PSQL=$SSTR_DBHOME/bin/psql
start_db

/usr/bin/su - $SSTR_DBOWNER -c ". $SSTR_DBBIN/postgres.env; $SSTR_PSQL -f $SSTR_DBHOME/nsm1/ddl/patchrm-01.sql" > /dev/null
