#-/*
#- Title  : tde_wall_bkp.ksh
#- Author : EXADIME LLC
#- Created: 22-Oct-2022
#- Updated: 22-Oct-2022
#- Release: 1.0.0
#- Purpose: This script does backup of TDE wallet files.
#- Commnet: Run ksh tde_wall_bkp.ksh -help for instructions.
#- History: N/A
#-*/

#Input
#0.Inputs: SID, Backup Directory, Retention

#Sanity
#1.Check if the requested database is up. If not, report error.
#2.Check for wallet root location in the database. If no root location, report error.
#3.Check for wallet files if exists in the above location and readable.
#4.Check for target location and writable.

#Action
#1.Tar followed by zip the wallet directory and copy to the target location.
#2.Remove the wallet backup files from the target location based on retention.

#!/usr/bin/ksh

#0.Functions
#set_dba_env <sid>
set_dba_env(){
#Header
#1.Input
if [ "${#}" -gt "1" ]; then
	echo "Too many arguments!"
	echo "Usage: set_dba_env [sid]"
	return
fi

#2.Sanity Checks
#2.1.Check for oratab.
if ! [ -f ${ora_tab} ]
then
	echo "oratab file does not exist!"
	return
fi

#2.2.Check for entries in oratab.
if test `grep -v '^#' ${ora_tab}|grep '^[^ ]'|grep -v '^-'|cut -f1 -d:|awk '{print;exit}'|wc -l` -ne 1
then
	echo "oratab file is blank!"
	return
fi

#2.3.Check for entry in oratab.
if [ "${#}" -eq "1" ]; then
	for i in `grep -v '^#' ${ora_tab}|grep '^[^ ]'|grep -v '^-'|grep ${1}`
	do
		a=`echo ${i}|awk -F: '{print $1}'`
		b=`echo ${i}|awk -F: '{print $2}'`
		
		if [ "${a}" = "${1}" ]
		then
			f=1
		fi
	done

	if [ ! "${f}" = "1" ]
	then
		echo "No entry found in oratab file for ${1}!"
		return
	fi
fi

#2.4.Validate entry in oratab.
if [ "${#}" -eq "1" ]; then
	for i in `grep -v '^#' ${ora_tab}|grep '^[^ ]'|grep -v '^-'|grep ${1}`
	do
		a=`echo ${i}| awk -F: '{print $1}'`
		b=`echo ${i}| awk -F: '{print $2}'`
		
		if [ "${a}" = "${1}" ]
		then
			if [[ "${b}" = "" || ! -d ${b} ]]
			then
				echo "Oracle home does not exist for oratab entry ${1}!"
				return
			fi
		fi	
	done
fi

#Body
#1.Set ORACLE_SID.
if [ "$#" != "0" ]
then
	ORACLE_SID=${1}
	shift
	export ORACLE_SID
fi

#2.Set ORACLE_HOME and replace old home in PATH.
if [ ${ORACLE_HOME:-0} = 0 ]; then
    OLDHOME=${PATH}
else
    OLDHOME=${ORACLE_HOME}
fi

for i in `grep -v '^#' ${ora_tab}|grep '^[^ ]'|grep -v '^-'|grep ${ORACLE_SID}`
do
	a=`echo ${i}|awk -F: '{print $1}'`
	b=`echo ${i}|awk -F: '{print $2}'`
	
	if [ "${a}" = "${ORACLE_SID}" ]
	then
		ORACLE_HOME=${b}; export ORACLE_HOME
	fi
done

case "${OLDHOME}" in
    "")	OLDHOME=${PATH} ;;	#This makes it so that null OLDHOME can't match
esac				#anything in next case statement

case "${PATH}" in
    *${OLDHOME}/*)	PATH=`echo ${PATH} | \
			    sed "s;${OLDHOME}/;${ORACLE_HOME}/;g"` ;;
    *${ORACLE_HOME}/bin*)	;;
    *:)			PATH=${PATH}${ORACLE_HOME}/bin: ;;
    "")			PATH=${ORACLE_HOME}/bin ;;
    *)			PATH=${PATH}:${ORACLE_HOME}/bin ;;
esac

export PATH 

#3.Set ORACLE_BASE.
if [ "${ORACLE_BASE}" = "" ]; then
	ORACLE_BASE=`dirname ${ORACLE_HOME}`; export ORACLE_BASE
fi

#4.Locate "osh" and exec it if found.
ULIMIT=`LANG=C ulimit 2>/dev/null`

if [ $? = 0 -a "${ULIMIT}" != "unlimited" ] ; then
  if [ "${ULIMIT}" -lt 2113674 ] ; then

    if [ -f ${ORACLE_HOME}/bin/osh ] ; then
	exec ${ORACLE_HOME}/bin/osh
    else
	for D in `echo ${PATH} | tr : " "`
	do
	    if [ -f ${D}/osh ] ; then
		exec ${D}/osh
	    fi
	done
    fi

  fi

fi

#5.Set LD_LIBRARY_PATH.
LD_LIBRARY_PATH=${ORACLE_HOME}/lib:/usr/openwin/lib:/usr/local/lib:/usr/lib:/usr/dt/lib; export LD_LIBRARY_PATH

#6.Set TNS_ADMIN.
if [ "${TNS_ADMIN}" = "" ]
then
	if ! [ -f ${TNS_ADMIN}/tnsnames.ora ]
	then
		TNS_ADMIN=${ORACLE_HOME}/network/admin; export TNS_ADMIN
	fi
fi

#7.Set NLS_LANG.
NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P1; export NLS_LANG

#8.Set OPatch location in PATH.
if [ "`echo ${PATH}|grep ${ORACLE_HOME}/OPatch`" = "" ]
then
	PATH=${PATH}:${ORACLE_HOME}/OPatch; export PATH
fi

#9.Display message.
echo "Switched to $ORACLE_SID db env."

}

#1.Declarations
ora_sid=""
bkp_dir=""
keep_days=""
label=""
title="Oracle Wallet Backup"
email=""
msg=""
sid=""
wallet_root=""

if [ "${#}" -lt "1" ]; then
	echo "Too few arguments! Run the below command for help."
	echo "ksh wallet_backup.ksh -help"
	return
fi

#2.Inputs
while [ "${#}" != "0" ]
do
        case ${1} in
                -sid|-s)
                shift
                if [ "$1" != "" ]
                then
                        ora_sid=${1}
                        shift
                fi
                ;;
                -bkpdir|-d)
                shift
                if [ "${1}" != "" ]
                then
                        bkp_dir=${1}
                        shift
                fi
                ;;                
                -keepdays|-k)
                shift
                if [ "${1}" != "" ]
                then
                        keep_days=${1}
                        shift
                fi
		;;
                -title|-t)
                shift
                if [ "${1}" != "" ]
                then
                        title=${1}
                        shift
                fi
                ;;
		-email|-e)
                shift
                if [ "${1}" != "" ]
                then
                        email=${1}
                        shift
                fi
                ;;
                -h|-help)
                echo ""
                echo "Argument             Description"
                echo "---------------------------------------------------------"
                echo "-sid|-s              SID."
                echo "-bkpdir|-d           Name of backup directory."
                echo "-keepdays|-k         No of days to keep file(s)."
		echo "-title|-t            Title of report."
		echo "-email|-e            E-mail for notification."
                exit 0;
                ;;
                *)
                echo "Bad argument: ${1}"
                echo "Use -help option to see correct usage."
                exit 0;
                ;;
        esac
done

time_stamp=`date +20%y%m%d%H%M%S`
log_file=/tmp/wallet_backup_${time_stamp}.log
echo "Wallet Backup Log:">${log_file}

if [ "${ora_sid}" = "" ]
then
	echo "Oracle SID entry is blank!" | tee -a ${log_file}
	if [[ "${title}" != "" && "${email}" != "" ]]; then
		cat ${log_file} |mailx -s "${title}" ${email}
	fi
	exit 0
else
	f=0
	for i in `grep -v '[#*]' ${ora_tab}|grep '^[^ ]'|grep ${ora_sid}`
	do
		a=`echo ${i}|awk -F: '{print $1}'`
		b=`echo ${i}|awk -F: '{print $2}'`
		
		if [ "${a}" = "${ora_sid}" ]
		then
			credentials="/ as sysdba"
			set_dba_env
			f=1
		fi	
	done

	if [ "${f}" = "0" ]
	then
		echo "Oracle SID entry is invalid!" | tee -a ${log_file}
		if [[ "${title}" != "" && "${email}" != "" ]]; then
			cat ${log_file} |mailx -s "${title}" ${email}
		fi
		exit 0
	fi
fi

if [ "${bkp_dir}" = "" ]
then
	echo "Backup directory entry is blank!" | tee -a ${log_file}
	if [[ "${title}" != "" && "${email}" != "" ]]; then
		cat ${log_file} |mailx -s "${title}" ${email}
	fi
	exit 0
else
	if ! [ -d ${bkp_dir} ]
	then
		echo "Backup directory does not exist!" | tee -a ${log_file}
		if [[ "${title}" != "" && "${email}" != "" ]]; then
			cat ${log_file} |mailx -s "${title}" ${email}
		fi
		exit 0
	else
		if ! [ -w ${bkp_dir} ]
		then
			echo "Backup directory is not writable!" | tee -a ${log_file}
			if [[ "${title}" != "" && "${email}" != "" ]]; then
				cat ${log_file} |mailx -s "${title}" ${email}
			fi
			exit 0
		fi		
	fi		
fi

if [ "${keep_days}" = "" ]
then
	echo "Keep days entry is blank!" | tee -a ${log_file}
	if [[ "${title}" != "" && "${email}" != "" ]]; then
		cat ${log_file} |mailx -s "${title}" ${email}
	fi
	exit 0
fi

#Sanity Checks
#1.Check if the requested database is up. If not, report error.
if [[ ! "${ora_sid}" = "" && ! "${ora_sid}" = "ALL" ]]; then
	if [[ `echo ${ora_sid}|grep "/"|wc -l` -ne 1 && `echo ${ora_sid}|grep "@"|wc -l` -ne 1 ]]; then
		if [ "`ps -eo user,pid,args|grep pmon_${ora_sid}|awk '$3 !~ /grep/ {print $3}'`" = "" ]
		then
			echo "Database ${sid} on `hostname` is not up!" | tee -a ${log_file}
			if [[ "${title}" != "" && "${email}" != "" ]]; then
				cat ${log_file} |mailx -s "${title}" ${email}
			fi
			exit 0
		fi
	fi	
fi

#2.Check for wallet root location in the database. If no root location, report error.
sqlplus -s ${credentials} |&
print -p -- 	"set echo off feed off serverout on term on lines 100 pages 0 pause off head off"
print -p -- 	"set sqlprompt ''"
print -p --	"col value format a40"
print -p --	"select value from v\$parameter where name='wallet_root';"
print -p -- "prompt rut"

p=1
while read -p line
do
	[[ "${line}" == "rut" ]] && break
	if [ ! "${line}" = "" ]; then
		wallet_root="${line}"
	fi
	p=$((${p}+1))
done

print -p -- exit

sleep 5

if [ "${wallet_root}" == "" ]; then
	echo "Wallet root value is null!" | tee -a ${log_file}
	if [[ "${title}" != "" && "${email}" != "" ]]; then
		cat ${log_file} |mailx -s "${title}" ${email}
	fi
fi

#3.Check for wallet files if exists in the above location and readable.
if [ "${wallet_root}" = "" ]
then
	echo "Backup directory entry is blank!" | tee -a ${log_file}
	if [[ "${title}" != "" && "${email}" != "" ]]; then
		cat ${log_file} |mailx -s "${title}" ${email}
	fi
	exit 0
else
	if ! [ -d ${bkp_dir} ]
	then
		echo "Backup directory does not exist!" | tee -a ${log_file}
		if [[ "${title}" != "" && "${email}" != "" ]]; then
			cat ${log_file} |mailx -s "${title}" ${email}
		fi
		exit 0
	else
		if ! [ -w ${bkp_dir} ]
		then
			echo "Backup directory is not writable!" | tree -a ${alt_file}
			if [[ "${title}" != "" && "${email}" != "" ]]; then
				cat ${log_file} |mailx -s "${title}" ${email}
			fi
			exit 0
		fi		
	fi		
fi

#Action
#1.Tar followed by zip the wallet directory and copy to the target location.
echo "Backing up wallet files..." >> ${log_file}
tar -cvf ${bkp_dir}/${ora_sid}_wallet_${time_stamp}.tar ${wallet_root} | tee -a ${log_file}

#2.Remove the wallet backup files from the target location based on retention.
echo "Removing old wallet backup files..." >> ${log_file}
find ${bkp_dir} -name "${ora_sid}_wallet_*" -mtime +${keep_days} -print | tee -a ${log_file}
find ${bkp_dir} -name "${ora_sid}_wallet_*" -mtime +${keep_days} -delete
