#!/bin/bash
#
###########################################################################
##  DPEXPIMP - Datapump export/import
##
## This script will export all BI related schemas schema
## In addition this script will make a zip archive with the catalog folder and cwallet.sso
##
##
## ABS Boxtel BV, The Netherlands 
## July 2023/CVI 
##  
## 1.0	- 31July2023	- Initial version
## 2.0  - 04August2025  - Explicit Bucket added in the script
##
##  CVI/ABS Laundry Business Solutions
###########################################################################

# Setting variables
export CUSTOMER_CODE=ABS                                # CUSTOMER Code add here
export ORACLE_BI_HOME=/u01/app/obiee			        # Location of OBI 	
export BACKUPLOCATION=/u02/oracle/dumpfiles			    # Export location for the script
export SYSPASS=hiltsNf9sWG2				                # BI SYS password <-------
export BUCKET_NAME="Dumpfiles_${CUSTOMER_CODE}_BI"      # Bucket name for OCI only
export PW_DEV_MDS=ABSDEV				                # Password of DEV_MDS schema
export PW_DEV_BIPLATFORM=ABSDEV				            # Password of DEV_BIPLATFORM schema
export PW_ABSDATAWAREHOUSE_V10=ABSDATAWAREHOUSE_V10		# Password of ABSDATAWAREHOUSE schema

# Oracle Database credentials
export FROM_SYSPWD=LAGAS8aR7X                           # Password of Oracle Database SYS Schema <------

#export MNTLOCATION=/mnt/bkp/BI                         # Added mount location for moving file after completion

# Create export of RPD
$ORACLE_BI_HOME/user_projects/domains/bi/bitools/bin/datamodel.sh downloadrpd -O $BACKUPLOCATION/backup.rpd -SI ssi -U SYS -P $SYSPASS -W abssys01 -Y

# Make LDIF file
export SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
export WLSTLOCATION=$ORACLE_BI_HOME/oracle_common/common/bin/wlst.sh
echo "connect('SYS','${SYSPASS}', 't3://localhost:9500');" > "$SCRIPTDIR/createLDIF.py"
echo "domainRuntime();" >> $SCRIPTDIR/createLDIF.py
echo "cd('/DomainServices/DomainRuntimeService/DomainConfiguration/bi/SecurityConfiguration/bi/DefaultRealm/myrealm/AuthenticationProviders/DefaultAuthenticator');" >> $SCRIPTDIR/createLDIF.py
echo "cmo.exportData('DefaultAtn','$BACKUPLOCATION/export.ldif', Properties());" >> $SCRIPTDIR/createLDIF.py
echo "exit();" >> $SCRIPTDIR/createLDIF.py
$ORACLE_BI_HOME/oracle_common/common/bin/wlst.sh $SCRIPTDIR/createLDIF.py
rm $SCRIPTDIR/createLDIF.py

# Make BAR file
export BARDIR="$BACKUPLOCATION/bardir"
mkdir -p "$BARDIR"

BAR_ERROR=false

rm -f "$BACKUPLOCATION/mnt_bar"

if [ -f "$ORACLE_BI_HOME/user_projects/domains/bi/bitools/bin/exportarchive.sh" ]; then
    if ! sh "$ORACLE_BI_HOME/user_projects/domains/bi/bitools/bin/exportarchive.sh" ssi "$BARDIR" encryptionpassword=OASBARabssys01; then
        echo "BAR export using exportarchive.sh failed."
        BAR_ERROR=true
    fi
else
    echo "exportServiceInstance ('$ORACLE_BI_HOME/user_projects/domains/bi','ssi','$BARDIR/workdir','$BARDIR/exportdir','','','',true,'ABSDATAWAREHOUSE_V10')" > "$SCRIPTDIR/createBAR.py"
    if ! "$ORACLE_BI_HOME/oracle_common/common/bin/wlst.sh" "$SCRIPTDIR/createBAR.py"; then
        echo "BAR export using wlst.sh failed."
        BAR_ERROR=true
    fi
    rm -f "$SCRIPTDIR/createBAR.py"
fi

# If BAR export failed, create error marker
if [[ "$BAR_ERROR" == true ]]; then
    echo "Creating BAR error marker: $BACKUPLOCATION/mnt_bar"
    touch "$BACKUPLOCATION/mnt_bar"
fi

# Make exports of the BI schema's
$SCRIPTDIR/dpexpimp.sh -ex -fu:ABSDATAWAREHOUSE_V10 -fp:$PW_ABSDATAWAREHOUSE_V10 -fn:ABSDATAWAREHOUSE_V10_$(date '+%A') -fd:$BACKUPLOCATION -ed:$BACKUPLOCATION
$SCRIPTDIR/dpexpimp.sh -ex -fu:DEV_MDS -fp:$PW_DEV_MDS -fn:DEV_MDS_$(date '+%A') -fd:$BACKUPLOCATION -ed:$BACKUPLOCATION
$SCRIPTDIR/dpexpimp.sh -ex -fu:DEV_BIPLATFORM -fp:$PW_DEV_BIPLATFORM -fn:DEV_BIPLATFORM_$(date '+%A') -fd:$BACKUPLOCATION -ed:$BACKUPLOCATION

# Check for errors in ABSDATAWAREHOUSE export log
logfile="ABSDATAWAREHOUSE_V10_$(date '+%A')_exp.log"
logpath="$BACKUPLOCATION/$logfile"
errorfile="$BACKUPLOCATION/mnt_error"

if [[ ! -f "$logpath" ]]; then
    echo "Log file not found: $logpath"
    exit 1
fi

# Search for expdp-related error codes
if grep -E "ORA-[0-9]{5}|UDE-[0-9]{5}" "$logpath" > /dev/null; then
    echo "Errors found in $logfile. Creating mnt_error marker."
    touch "$errorfile"
else
    echo "No expdp errors found in $logfile."
    [[ -f "$errorfile" ]] && rm -f "$errorfile"
fi

# Create zip file
ZIPNAME="$BACKUPLOCATION/BI_$(date '+%A').zip"
rm -f "$ZIPNAME"
cp "$ORACLE_BI_HOME/user_projects/domains/bi/config/fmwconfig/bootstrap/cwallet.sso" "$BACKUPLOCATION"

cd "$BACKUPLOCATION"

zip -r "$ZIPNAME" backup.rpd bardir cwallet.sso export.ldif *_$(date '+%A').dmp.gz *_$(date '+%A')_exp.log || {
    echo "ZIP creation failed."
    exit 1
}
rm -r backup.rpd bardir cwallet.sso export.ldif *_$(date '+%A').dmp.gz *_$(date '+%A')_exp.log

# Copy zip to OCI Bucket - - - For installing it at customer side please commnet the IF below
if ! oci os object put -ns axrnmo3hd7kn -bn "$BUCKET_NAME" --file "$ZIPNAME" --name "BI_$(date '+%A').zip" --force; then
    echo "Failed to upload ZIP to OCI"
    exit 1
fi
echo "Upload successful and verified: Object size matches local file size"

# Move zip to mount location
#[ -d $MNTLOCATION ] && mv -f $ZIPNAME $MNTLOCATION && touch $BACKUPLOCATION/mnt_ok

# Create mnt_ok after task completion
echo Daily Export succesfuly Done
touch $BACKUPLOCATION/mnt_ok