#!/bin/ksh
########################################################################
#*                                                                     *
#*             Copyright (c) Ultra Electronics Limited 2007            *
#*                         All rights reserved                         *
#*                                                                     *
#***********************************************************************
#*
#* Filename:           database_backup.ksh
#* Subsystem Name:     RMAN backup
#* Originating Author: Gary Roberts
#* Design Reference:   UAS/FALCP/SY/2478
#*
#***********************************************************************
#*
#* Description:
#*   This script is a wrapper script designed to perform pre-backup
#*   checks and then call the main backup script rman_db_backup.ksh.
#*   The return code of rman_db_backup.ksh script is checked, and 
#*   if it is zero, the backuppieces will be moved to tape if the 
#*   "-t" command-line option was supplied.
#*
#*   
#* Usage:
#*     database_backup.ksh -d <backup directory> [-t <tape device>] [-r] 
#*     [-b <FULL|ARCHIVELOG>] [-c <user>/<pwd>@<recovery_cat_tnsname>]
#*     [-e <expired data directory>]
#*
#* Environment Variables:
#*     This script itself does not require any enviroment variables to
#*     be set, however the scripts rman_db_backup.ksh and
#*     move_files_to_tape.ksh that are invoked by this script do 
#*     require certain environment variables to be set, which are
#*     described in the headers of those scripts.
#*
#*
#* Options:
#*     -d The directory into which RMAN should put its backuppieces.
#*
#*     -c The recovery catalog connection string, in the form:
#*        <username>/<password>@<tnsname> 
#*
#*     -t This option governs whether or not the backup will be moved
#*        to tape. The path to the tape device should be supplied.
#*
#*     -r If this option is supplied, when the backup has been moved to
#*        tape the tape will be retained in the drive for future use
#*        i.e. it will not be ejected.
#*
#*     -b This option gives the backup type which, at this stage, can be
#*        FULL or ARCHIVELOG. For FULL backups, if a recovery catalog is
#*        not supplied (using the -c option), the backup type is
#*        automatically set to FULL_NOCAT. 
#*     
#*     -e Specify an optional path to a directory which will be moved
#*        to tape along with the RMAN files. This is intended to be used
#*        for the directoty used for expired data exports that have been
#*        created by the Archive process.
#*
#***********************************************************************
#* Modification History
#*
#* Rel Date/Time      Proj/Id   CA Ref/Details Of Change
#* --- -------------- --------  ---------------------------------------
#* 1   15/05/07 17:00 RMAN      SY02478 - UltraTrak RMAN backup process
#*
#**********************************************************************/

#######################################################################
# FUNCTIONS
#######################################################################

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Function to display USAGE when this script is called incorrectly.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f_usage()
{
logger "DB_BKUP: USAGE: $0 -d <backup directory> [-t <tape device>] "\
     "[-r] [-b <FULL|ARCHIVELOG>] "\
     "[-c <user>/<pwd>@<recovery_cat_tnsname>] "\
     "[-e <expired data directory>] "
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Generate a name for the RMAN backup log
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

f_name_logfile()
{
  DT=`date +'%D:%H%M'|sed s!/!_!g`
  LOGFILE=${BACKUP_DIR}/rman_${DT}_${ORACLE_SID}.log
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Find out if the database role is PRIMARY or PHYSICAL_STANDBY
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f_db_role()
{
TEMPFILE="/tmp/db_role$$.lst"
   # Write the database role to a file.
      sqlplus -s '/ as sysdba' << EOF > /dev/null
      set head off
      set feedback off
      spool ${TEMPFILE}
        SELECT database_role FROM v\$database;
      spool off
EOF

 # Read the database_role from the file
  DB_ROLE=`cat ${TEMPFILE}`
  DB_ROLE=`echo ${DB_ROLE} | sed "s/ //g"`

  # Delete the file
  rm -f ${TEMPFILE}

echo ${DB_ROLE}
  if [[ ${DB_ROLE} != "PRIMARY" && ${DB_ROLE} != "PHYSICAL_STANDBY" ]];
  then
    logger "DB_BKUP: database_backup.ksh: ERROR: Unable to determine "\
           "database type. Backup aborted".
    exit 1
  fi
}

#######################################################################
# END OF FUNCTIONS
#######################################################################


#######################################################################
#
# MAIN PROGRAM
#
#######################################################################

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Assign default values to variables if required and then overwrite 
# these with command line options, if they have been passed in.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

USE_TAPE="yes"
RETAIN_TAPE="no"
BACKUP_TYPE="full"
TAPE_DEVICE="/dev/null"
EXPIRED_DIR="/dev/null"

while getopts d:rt:e:b:c: options
do
  case $options in
    b) BACKUP_TYPE=`echo $OPTARG | tr [A-Z] [a-z]` ;;
    c) RECOVERY_CATALOG=$OPTARG ;;
    d) BACKUP_DIR=$OPTARG ;;
    e) EXPIRED_DIR=$OPTARG ;;
    r) RETAIN_TAPE="yes" ;;
    t) TAPE_DEVICE=$OPTARG ;;
  [?]) f_usage
       exit 2 ;;
  esac
done

if [[ $? -ne 0 ]];
then
   logger "DB_BKUP: database_backup.ksh: ERROR: Unable to interpret "\
          "command line options"
   exit 3
fi

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Check that all of the mandatory variables have been passed in.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if [[ $BACKUP_DIR = "" ]];
then
   f_usage
   exit 4 
fi

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Generate a name for the log file. This will be passed to both
# rman_db_backup.ksh (which writes the log) and move_files_to_tape.ksh,
# which reads it.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

f_name_logfile
if [[ $? -ne 0 ]];
then
    logger "DB_BKUP: database_backup.ksh: An error occurred whilst "\
           "generating the logfile name".
    exit 5
fi

#
# Generate a string of the command required to call rman_db_backup.ksh 
#
COMMAND="rman_db_backup.ksh -d ${BACKUP_DIR} -l ${LOGFILE} -b ${BACKUP_TYPE}"

if [[ ${RECOVERY_CATALOG} != "" ]];
then
    COMMAND=`echo "${COMMAND} -c ${RECOVERY_CATALOG}"`
fi

/bin/ksh $COMMAND 

if [[ $? -ne 0 ]];
then
    logger "DB_BKUP: database_backup.ksh: ERROR: The return code of "\
           "the rman_db_bkup.ksh script was non-zero. The rest of the "\
           "backup process will now be aborted." 

    exit 6
fi  


#
# Check that the database isn't a DataGuard standby database before 
# moving to tape
#
f_db_role
if [[ ${DB_ROLE} != "PRIMARY" ]];
then
    echo "DB_ROLE is"
    echo x${DB_ROLE}x
    exit 7 
fi
if [[ ${TAPE_DEVICE} != "/dev/null" ]]
then

    if [[ ${RETAIN_TAPE} = "yes" ]]
    then
        RETAIN_COMMAND="-r"
    else
        RETAIN_COMMAND=""
    fi
  
    if [[ ${EXPIRED_DIR} != "/dev/null" ]]
    then
        EXPIRED_COMMAND="-e ${EXPIRED_DIR}"
    else 
        EXPIRED_COMMAND=""
    fi

    move_files_to_tape.ksh -l ${LOGFILE} ${RETAIN_COMMAND}\
                                      ${EXPIRED_COMMAND} -t ${TAPE_DEVICE}

    if [[ $? -ne 0 ]];
    then
        logger "DB_BKUP: database_backup.ksh: ERROR: The return code of"\
               "the script move_files_to_tape.ksh was non-zero."
        exit 8
    fi
fi

exit 0
