#!/bin/ksh

# Script checks the free space of the Oracle archivelog mountpoint.
# If the size is above the given threshold an email notification is sent
# and an RMAN backup of the log files is started
# This script can be modified, by removing the threshold requiremnet and
# the "delete all input" and used as a regular Archivelog file backup.
# backup_archivelog_space.sh

# Set environment variables

export ORACLE_SID=ORADB1
export ORACLE_HOME=/u01/app/oracle/product/10.2.0/dbhome
export PATH=$PATH:$ORACLE_HOME/bin

host=$(hostname)
filext=$(date +%m%d%y'_'%H%M)

# First we determine how much space is being used in the archivelog destinataion

USED=$(df -h /oracle/$ORACLE_SID/oraarch/ |grep -v Used% |awk '{print substr($5,1,length($5)-1)}')

# check that no other rman processes are running

rmancheck=$(ps -ef | grep "rman" | grep -v grep | awk '{print $8}')
pcheck=$(echo $rmancheck | awk '{print $1}')
if [[ $pcheck == rman ]]; then
count=0;
while (( count < 20)) && [[ $pcheck == rman ]]; do
         sleep 60
         rmancheck=$(ps -ef | grep "rman" | grep -v grep | awk '{print $8}')
         pcheck= $(echo $rmancheck | awk '{print $1}')
         $((count += 1))
     done
         rmancheck=$(ps -ef | grep "rman" | grep -v grep | awk '{print $8}')
	 pcheck=$(echo $rmancheck | awk '{print $1}')
     if [[ $pcheck != rman ]] then
	   :
     else
	 (echo 'backup conflict') | mail -s "$ORACLE_SID Archivelog backup conflict.$USED percent full" \
             $(cat /u01/app/oracle/admin/$ORACLE_SID/scripts/oracle/alert.lst)
fi

# If the used space is greater than or equal to 70%, an RMAN backup will start
# Set used percentage threshold for script execution

if  (( $USED >= 70)) && [[ $pcheck != rman ]]   then

# Start RMAN process. Connect to database(ORADB1) and to RMAN catalog(rcat). Archivelog file name includes
# %d: database name, %T: date format yyyymmdd, %U: system generated unique id
# remove quotes from ""<""


rman<"<"EOJ

spool log to '/u01/app/oracle/admin/$ORACLE_SID/adminlogs/archive_$filext.log';

connect target sys/password@ORADB1
connect catalog rmanadmin/password@rcat

run
{crosscheck archivelog all;}

run
{delete expired archivelog all;}
yes

configure default device type to 'SBT_TAPE';
configure device type 'SBT_TAPE' parallelism 2;

show all;

run{
backup format 'archive_%d_%T_%U.arc'
archivelog all
delete all input;}

exit

EOS

# Email output file as a Word document attachment

fileloc='/u01/app/oracle/admin/'$ORACLE_SID'/adminlogs/archive_'$filext'.log'
filename='archive_'$filext'.log.doc'

$(chmod 755 $fileloc)

 (cat /u01/app/oracle/admin/$ORACLE_SID/scripts/backup_scripts/archive_mail.txt; uuencode $fileloc $filename) \
 |mail -s "$host Archivelog Backup Initiated Filesystem $USED Percent Full" \
 $(cat /u01/app/oracle/admin/$ORACLE_SID/scripts/mail.lst)

fi

exit