#!/bin/bash

if [[ $# == 2 ]]
then
  rcvfile=$1
  orasid=$2
else
 echo "usage $0 RCV_FILE ORACLE_SID"
 exit
fi

#
#  if rcvfile not found, prepend path of $0, retest
#
[[ -f $rcvfile ]]
if [ "$?" != 0 ]
then
        dirpath=`dirname $0`
        if [ -f "${dirpath}/${rcvfile}" ]
        then
                rcvfile="${dirpath}/${rcvfile}"
        else
                echo "ERROR: ${rcvfile} not found"
                exit
        fi
fi

#
# check for digits only
#
function is_digit
{
echo $1|gawk ' { if ($0 ~ /^[0-9]+$/)
                    print 1
                  else
                    print 0 } '
} # end is_digit


#
# determine the ORACLE_HOME for the SID passed in.
#   * RAC test for root of SID removing last digit
#
export ORACLE_SID=$orasid
_orasid0=${orasid:0:${#orasid}-1}
_orasid1=${orasid:${#orasid}-1:${#orasid}}
OH=`/usr/local/bin/dbhome $orasid`
if [ "$?" != 0 ] && [ $(is_digit $_orasid1) == 1 ]
then
        OH=`/usr/local/bin/dbhome $_orasid0`
        if [ "$?" != 0 ]
        then
                echo "error: cannot find ${orasid} or ${_orasid0} in oratab file."
                exit
        else
                echo "using ${OH} for SID ${_orasid0} found in oratab."
                export ORACLE_HOME=$OH
        fi
else
        echo "using ${OH} for SID ${orasid} found in oratab."
        export ORACLE_HOME=$OH
fi

#
# make sure rman command exists.
#
if [ -f $ORACLE_HOME/bin/rman ]
then
        echo "connecting to $ORACLE_SID using $ORACLE_HOME/bin/rman"
else
        echo "RMAN not found in $ORACLE_HOME/bin"
fi

logfile=/var/log/oracle/rman_${orasid}.log
errfile=/var/log/oracle/rman_${orasid}.err
arcfile="/var/log/oracle/rman_${orasid}.`date +%a`"


NLS_DATE_FORMAT='DD-MON-RR HH24:MI.SS'; export NLS_DATE_FORMAT

$ORACLE_HOME/bin/rman log $logfile nocatalog @$rcvfile
/bin/egrep "RMAN-|ORA-" $logfile > $errfile
/bin/cp $logfile $arcfile
if [ -s $errfile ]
then
        /bin/mail -s "Oracle Backup $ORACLE_SID" Oracle_rman@datapipe.com < $logfile
fi

# archive the control files for a week.
today=`/bin/date +"%Y-%m-%d"`
dumpsdir="/dumps/${ORACLE_SID}"
ctrlbase="${dumpsdir}/${ORACLE_SID}-control"
if [ -f "${ctrlbase}.bak" ]
then
        /bin/cp ${ctrlbase}.bak ${ctrlbase}_bak.${today}
fi

if [ -f "${ctrlbase}.trc" ]
then
        /bin/cp ${ctrlbase}.trc ${ctrlbase}_trc.${today}
fi

