# Create log file with timestamp in a persistent location
LOG_DIR="/var/log/parablu"
LOG_FILE="$LOG_DIR/parablu_script_$(date +%Y%m%d_%H%M%S).log"

# Create log directory if it doesn't exist
mkdir -p "$LOG_DIR" 2>/dev/null || {
    # Fallback to /var/log if we can't create /var/log/parablu
    LOG_FILE="/var/log/parablu_script_$(date +%Y%m%d_%H%M%S).log"
}

echo "Script execution started. Detailed logs will be written to: $LOG_FILE"

# Function to log commands while keeping echo visible
log_exec() {
    echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE" 2>&1
    "$@" >> "$LOG_FILE" 2>&1
}

PARABLU_COMPONENT_SCRIPT_PATH=../../config/parablu_component_config.sh
PARABLU_CONFIG_SCRIPT_PATH=../../config/parablu_config.sh

source $PARABLU_COMPONENT_SCRIPT_PATH
source $PARABLU_CONFIG_SCRIPT_PATH

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "3 1" ]; then
        FILE2=Portal_V2.zip
        if [ -f "$FILE2" ]; then
                echo "Setting up Portal V2..."
                log_exec rm -rf /var/www/portal/*
                log_exec cp -r Portal_V2.zip /var/www/portal/
                cd /var/www/portal/
                        ##new portal extraction
                        echo "Extracting Portal V2..."
                        log_exec unzip -oqq Portal_V2.zip
                        log_exec rm -rf Portal_V2.zip
                        log_exec chmod -R 755 *
                        log_exec chown -R www-data:www-data *
                cd -

                        ##newportal config.json changes
                        echo "Configuring Portal V2 settings..."
                        log_exec sed -i "s|devangular|$NG_IP|"  /var/www/portal/assets/config.json
                        log_exec sed -i "s|multicloud|$CLOUD_NAME|"  /var/www/portal/assets/config.json
                        log_exec sed -i "s|pbengg-redirect.parablu.com|$NG_RL|" /var/www/portal/assets/config.json
                        log_exec sed -i "s|mycloud.parablu.com|$BLUVAULT_IP|" /var/www/portal/assets/config.json

                        ##new portal index.html changes
                        log_exec sed -i '6s|<base href="/">|<base href="/devangular/portal/">|' /var/www/portal/index.html
                        log_exec sed -i "s|devangular|$NG_IP|" /var/www/portal/index.html

			##old .htacess
			log_exec sed -i "s|HOST|$NG_IP|"  indexnew.html
                	log_exec cp -rp  indexnew.html index.html
                	log_exec cp -rp index.html /var/www/

        fi
fi

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "3 1" ]; then

         ##new portal .htaccess
                        echo "Configuring portal .htaccess..."
                        log_exec cp -rp  htaccessnginix .htaccess
                        log_exec chown -R  www-data:www-data .htaccess
                        log_exec cp -rp .htaccess /var/www/portal/
fi

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "3 1" ]; then
	dbport=$(grep port: /etc/mongod.conf)
        MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')

        echo "Configuring Tomcat services..."
        #log_exec cp -r /parablu/pb-cloudproperty.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
        #log_exec cp -r /parablu/pb-credential.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
	#log_exec cp -r /parablu/paracloud-pb-credential/pb-credential.properties /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/
	#log_exec cp -r /parablu/paracloudjob-pb-credential/pb-credential.properties /var/lib/tomcat-job1/webapps/paracloudjob/WEB-INF/classes/
	#log_exec cp -r /parablu/support-pb-credential/pb-credential.properties /var/lib/tomcat-pcb1/webapps/support/WEB-INF/classes/
	#log_exec cp -r /parablu/paramail-pb-credential/pb-credential.properties /var/lib/tomcat-pcb1/webapps/paramail/WEB-INF/classes/

        echo "Stopping Tomcat services..."
        log_exec service tomcat-pcb1 stop
        log_exec service tomcat-job1 stop
        sleep 2s
        cd /var/lib/tomcat-pcb1/webapps/
        log_exec rm -rf paralite.war
        sleep 1s
        cd -
        sleep 2s
        echo "Starting Tomcat services..."
        log_exec service tomcat-pcb1 restart
        log_exec service tomcat-job1 restart
fi

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "3" ] || [ "$SERVER_TYPE" == "3 1" ]; then
	dbport=$(grep port: /etc/mongod.conf)
        MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')

        echo "Setting up Excel files..."
        log_exec chown -R tomcat:parablu Users.xlsx
        log_exec cp -rp Users.xlsx /parablu/bkpOverview/

        log_exec chown -R tomcat:parablu bulkCreateUsers.xlsx
        log_exec cp -rp bulkCreateUsers.xlsx /parablu/bkpOverview/

        log_exec chown -R tomcat:parablu  bulkBlockUnblockDeleteAssets.xlsx
        log_exec cp -rp bulkBlockUnblockDeleteAssets.xlsx /parablu/bkpOverview/

        log_exec chown -R tomcat:parablu bulkBlockUnblockDeleteUsers.xlsx
        log_exec cp -rp bulkBlockUnblockDeleteUsers.xlsx /parablu/bkpOverview/

        log_exec chown -R tomcat:parablu bulkBlockUnblockDeleteUsersAdvanced.xlsx
        log_exec cp -rp bulkBlockUnblockDeleteUsersAdvanced.xlsx /parablu/bkpOverview/

	log_exec chown -R tomcat:parablu  bulkBackupTargetMapping.xlsx
        log_exec cp -rp bulkBackupTargetMapping.xlsx /parablu/bkpOverview/

fi

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "3 1" ] || [ "$SERVER_TYPE" == "2" ]; then
    # ==========================================
    # COMMON CHANGES FOR SINGLE AND MULTI TENANCY SETUPS
    # ==========================================

    echo "Stopping Tomcat services..."
    log_exec service tomcat-pcb1 stop
    log_exec service tomcat-job1 stop
    sleep 2s
    cd /var/lib/tomcat-pcb1/webapps/
    log_exec rm -rf paralite.war
    sleep 1s
    cd -
    sleep 2s
    echo "Starting Tomcat services..."
    log_exec service tomcat-pcb1 restart
    log_exec service tomcat-job1 restart

    # ==========================================
    # 11-09-2025: PC-409 MongoDB Configuration Patch
    # ==========================================
    PB_CREDS_FILES=(
        "/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-job1/webapps/paracloudjob/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-pcb1/webapps/paramail/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-pcb1/webapps/support/WEB-INF/classes/pb-credential.properties"
    )

    BLUKRYPT_FILE="/var/lib/tomcat-pcb1/webapps/BluKryptBuilder/WEB-INF/classes/privacygateway.properties"

    for PB_CREDS_FILE in "${PB_CREDS_FILES[@]}"; do
        if [ ! -f "$PB_CREDS_FILE" ]; then
            echo "Warning: File $PB_CREDS_FILE does not exist - skipping."
            continue
        fi

        log_exec sed -i "s/27017/48765/g" "$PB_CREDS_FILE"
        log_exec sed -i '/^db_host[0-9]*=/s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/localhost/g' "$PB_CREDS_FILE"
    done

    # Handle BluKryptBuilder file separately - only change local_db_port
    if [ -f "$BLUKRYPT_FILE" ]; then
        echo "Processing BluKryptBuilder file..."
        log_exec sed -i 's/^local_db_port=27017$/local_db_port=48765/g' "$BLUKRYPT_FILE"
        echo "Updated local_db_port in $BLUKRYPT_FILE"
    else
        echo "Warning: File $BLUKRYPT_FILE does not exist - skipping."
    fi

    # ==========================================
    # Set ownership for LicenseKey directory
    # ==========================================
    echo "=== Setting ownership for LicenseKey directory ==="
    if [ -d "/parablu/LicenseKey/encryptedFiles" ]; then
        log_exec chown -R tomcat:tomcat /parablu/LicenseKey/encryptedFiles/
        echo "Ownership set successfully for /parablu/LicenseKey/encryptedFiles/"
    else
        echo "Warning: Directory /parablu/LicenseKey/encryptedFiles/ not found. Skipping ownership change."
    fi

    # ==========================================
    # Update Apache Cache-Control headers
    # ==========================================
    echo "=== Updating Apache Cache-Control headers ==="
    APACHE_CONFIG_FILES=(
        "/etc/apache2/sites-enabled/000-default.conf"
        "/etc/apache2/sites-enabled/default-ssl.conf"
        "/etc/apache4/sites-enabled/000-default.conf"
    )

    for APACHE_FILE in "${APACHE_CONFIG_FILES[@]}"; do
        if [ -f "$APACHE_FILE" ]; then
            echo "Processing $APACHE_FILE..."

            # Check for and replace both variations of Cache-Control header
            UPDATED=false

            # Check for version with "max-age=84600, no-cache"
            if grep -q 'Header set Cache-Control "max-age=84600, no-cache"' "$APACHE_FILE"; then
                log_exec sed -i 's/Header set Cache-Control "max-age=84600, no-cache"/Header set Cache-Control "no-store, no-cache, must-revalidate"/' "$APACHE_FILE"
                echo "Cache-Control header (with no-cache) updated successfully in $APACHE_FILE"
                UPDATED=true
            fi

            # Check for version with just "max-age=84600"
            if grep -q 'Header set Cache-Control "max-age=84600"' "$APACHE_FILE"; then
                log_exec sed -i 's/Header set Cache-Control "max-age=84600"/Header set Cache-Control "no-store, no-cache, must-revalidate"/' "$APACHE_FILE"
                echo "Cache-Control header (max-age only) updated successfully in $APACHE_FILE"
                UPDATED=true
            fi

            if [ "$UPDATED" = false ]; then
                echo "No matching Cache-Control header found in $APACHE_FILE - no changes made."
            fi
        else
            echo "Warning: File $APACHE_FILE not found. Skipping."
        fi
    done

    echo "Apache configuration update completed."

    # ==========================================
    # Update Apache Directory Configurations
    # ==========================================
    echo "=== Updating Apache Directory Configurations ==="

    # 1. Remove Directory block from /etc/apache4/apache4.conf
    APACHE4_CONF="/etc/apache4/apache4.conf"
    if [ -f "$APACHE4_CONF" ]; then
        echo "Processing $APACHE4_CONF..."

        # Check if the Directory block exists
        if grep -q '<Directory /var/www/>' "$APACHE4_CONF"; then
            # Create backup
            log_exec cp "$APACHE4_CONF" "${APACHE4_CONF}.backup_$(date +%Y%m%d_%H%M%S)"

            # Remove the Directory block (including all lines between <Directory> and </Directory>)
            log_exec sed -i '/<Directory \/var\/www\/>/,/<\/Directory>/d' "$APACHE4_CONF"
            echo "Removed existing <Directory /var/www/> block from $APACHE4_CONF"
        else
            echo "No existing <Directory /var/www/> block found in $APACHE4_CONF"
        fi
    else
        echo "Warning: File $APACHE4_CONF not found - skipping."
    fi

    # 2. Remove Directory block from /etc/apache4/sites-enabled/000-default.conf
    APACHE4_ENABLED_DEFAULT="/etc/apache4/sites-enabled/000-default.conf"
    if [ -f "$APACHE4_ENABLED_DEFAULT" ]; then
        echo "Processing $APACHE4_ENABLED_DEFAULT..."

        if grep -q '<Directory /var/www/portal>' "$APACHE4_ENABLED_DEFAULT"; then
            log_exec cp "$APACHE4_ENABLED_DEFAULT" "${APACHE4_ENABLED_DEFAULT}.backup_$(date +%Y%m%d_%H%M%S)"
            log_exec sed -i '/<Directory \/var\/www\/portal>/,/<\/Directory>/d' "$APACHE4_ENABLED_DEFAULT"
            echo "Removed <Directory /var/www/portal> block from $APACHE4_ENABLED_DEFAULT"
        else
            echo "No <Directory /var/www/portal> block found in $APACHE4_ENABLED_DEFAULT"
        fi
    else
        echo "Warning: File $APACHE4_ENABLED_DEFAULT not found - skipping."
    fi

    # 3. Remove Directory block from /etc/apache4/sites-available/000-default.conf
    APACHE4_AVAILABLE_DEFAULT="/etc/apache4/sites-available/000-default.conf"
    if [ -f "$APACHE4_AVAILABLE_DEFAULT" ]; then
        echo "Processing $APACHE4_AVAILABLE_DEFAULT..."

        if grep -q '<Directory /var/www/portal>' "$APACHE4_AVAILABLE_DEFAULT"; then
            log_exec cp "$APACHE4_AVAILABLE_DEFAULT" "${APACHE4_AVAILABLE_DEFAULT}.backup_$(date +%Y%m%d_%H%M%S)"
            log_exec sed -i '/<Directory \/var\/www\/portal>/,/<\/Directory>/d' "$APACHE4_AVAILABLE_DEFAULT"
            echo "Removed <Directory /var/www/portal> block from $APACHE4_AVAILABLE_DEFAULT"
        else
            echo "No <Directory /var/www/portal> block found in $APACHE4_AVAILABLE_DEFAULT"
        fi
    else
        echo "Warning: File $APACHE4_AVAILABLE_DEFAULT not found - skipping."
    fi

    # 4. Remove Directory block from /etc/apache4/sites-available/default-ssl.conf
    APACHE4_SSL_CONF="/etc/apache4/sites-available/default-ssl.conf"
    if [ -f "$APACHE4_SSL_CONF" ]; then
        echo "Processing $APACHE4_SSL_CONF..."

        if grep -q '<Directory /var/www/portal/>' "$APACHE4_SSL_CONF"; then
            log_exec cp "$APACHE4_SSL_CONF" "${APACHE4_SSL_CONF}.backup_$(date +%Y%m%d_%H%M%S)"
            log_exec sed -i '/<Directory \/var\/www\/portal\/>/,/<\/Directory>/d' "$APACHE4_SSL_CONF"
            echo "Removed <Directory /var/www/portal/> block from $APACHE4_SSL_CONF"
        else
            echo "No <Directory /var/www/portal/> block found in $APACHE4_SSL_CONF"
        fi
    else
        echo "Warning: File $APACHE4_SSL_CONF not found - skipping."
    fi

    # 5. Add new Directory configuration to /etc/apache4/apache4.conf
    if [ -f "$APACHE4_CONF" ]; then
        echo "Adding new Directory configuration to $APACHE4_CONF..."

        # Check if the new configuration already exists
        if grep -q "Options -Indexes -MultiViews" "$APACHE4_CONF"; then
            echo "New Directory configuration already exists in $APACHE4_CONF - skipping."
        else
            # Append the new Directory block at the end of the file
            cat >> "$APACHE4_CONF" << 'APACHE_DIR_EOF'

<Directory /var/www/>
        Options -Indexes -MultiViews
        AllowOverride None
        DirectoryIndex index.html
        Require all granted
        DirectorySlash Off
        RewriteEngine On
       RewriteCond %{REQUEST_URI} !^/portal/.*
       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteRule ^ index.html [L]
       RewriteCond %{REQUEST_URI} ^/portal/.*
       RewriteCond %{REQUEST_FILENAME} !-f
       RewriteCond %{REQUEST_FILENAME} !-d
       RewriteRule ^  /portal/index.html [L]
</Directory>
APACHE_DIR_EOF

            echo "New Directory configuration added to $APACHE4_CONF"
            echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Added new Directory config to apache4.conf" >> "$LOG_FILE"
        fi
    fi

    echo "Apache Directory configuration update completed."

    # ==========================================
    # Update /var/www/index.html with Redirect
    # ==========================================
    echo "=== Updating /var/www/index.html with redirect code ==="

    INDEX_HTML="/var/www/index.html"

    if [ -f "$INDEX_HTML" ]; then
        echo "Processing $INDEX_HTML..."

        # Create backup
        log_exec cp "$INDEX_HTML" "${INDEX_HTML}.backup_$(date +%Y%m%d_%H%M%S)"
        echo "Backup created for $INDEX_HTML"

        # Replace entire content with new redirect HTML
        cat > "$INDEX_HTML" << 'INDEX_HTML_EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Redirecting Page</title>
    <script type="text/javascript">
        // This script will run as soon as the browser processes it
        window.location.href = "./portal/";
    </script>
</head>
<body>
    <p>If you are not redirected automatically, follow this <a href="./portal/">link to the portal</a>.</p>
</body>
INDEX_HTML_EOF

        echo "Successfully updated $INDEX_HTML with redirect code"
        echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Updated /var/www/index.html with portal redirect" >> "$LOG_FILE"
    else
        echo "Warning: File $INDEX_HTML not found - skipping."
    fi

    echo "/var/www/index.html update completed."

    echo "Restarting Apache 4..."
    if service apache4 restart >> "$LOG_FILE" 2>&1; then
        echo "Apache 4 restarted successfully"
    else
        echo "ERROR: Failed to restart Apache 4"
        echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] ERROR: Apache 4 restart failed" >> "$LOG_FILE"
    fi

    # ==========================================
    # 14-10-2025: Add <bean> configuration.
    # ==========================================
    XML_FILES=(
        "/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/spring-config/dao-context.xml"
        "/var/lib/tomcat-job1/webapps/paracloudjob/WEB-INF/classes/spring-config/dao-context.xml"
    )

    for XML_FILE in "${XML_FILES[@]}"; do
        if [ ! -f "$XML_FILE" ]; then
            echo "File not found: $XML_FILE skipping."
            continue
        fi

        echo "Processing $XML_FILE..."

        if grep -q 'id="syncFileDao"' "$XML_FILE"; then
            echo "Warning: syncFileDao bean already exists in $XML_FILE. No changes made."
        else
            sed -i '/<\/beans>/i \
                    <bean id="syncFileDao" class="com.parablu.pcsd.dao.impl.SyncFileDaoImpl">\
                            <property name="paracloudMongoFactoryUtils" ref="paracloudMongoFactoryUtils" />\
                    </bean>' "$XML_FILE"

            echo "syncFileDao bean successfully added to $XML_FILE"
        fi
    done

    # ==========================================
    # Move SMTP_CREDENTIALS from parablu to parablu001 DB
    # ==========================================
    echo "=== Moving SMTP_CREDENTIALS collection from parablu to parablu001 ==="

    # Get MongoDB port
    dbport=$(grep port: /etc/mongod.conf)
    MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')

    echo "Moving SMTP_CREDENTIALS collection..."

    mongo --quiet --norc localhost:"$MONGODB_PORT" -u "neil" -p "parablu" --authenticationDatabase "admin" > /dev/null 2>&1 << 'EOF'
use parablu
var sourceCount = db.SMTP_CREDENTIALS.countDocuments({})
if (sourceCount > 0) {
    print("Found " + sourceCount + " documents in parablu.SMTP_CREDENTIALS")
    var data = db.SMTP_CREDENTIALS.find().toArray()
}
use parablu001
if (sourceCount > 0) {
    var bulkOps = data.map(function(doc) {
        return {
            replaceOne: {
                filter: { _id: doc._id },
                replacement: doc,
                upsert: true
            }
        }
    })
    var result = db.SMTP_CREDENTIALS.bulkWrite(bulkOps)
    print("Upserted " + (result.upsertedCount + result.modifiedCount) + " documents into parablu001.SMTP_CREDENTIALS")
}
use parablu
if (sourceCount > 0) {
    db.SMTP_CREDENTIALS.drop()
    print("Dropped SMTP_CREDENTIALS collection from parablu database")
    print("Collection successfully moved from parablu to parablu001")
} else {
    print("No SMTP_CREDENTIALS collection found in parablu database - nothing to move")
}
EOF

    echo "SMTP_CREDENTIALS collection move operation completed."

    # ==========================================
    # Copy CLOUD_PROPERTIES from parablu to parablu001 DB
    # ==========================================
    echo "=== Copying CLOUD_PROPERTIES collection from parablu to parablu001 ==="

    echo "Copying CLOUD_PROPERTIES collection..."

    mongo --quiet --norc localhost:"$MONGODB_PORT" -u "neil" -p "parablu" --authenticationDatabase "admin" > /dev/null 2>&1 << 'EOF'
use parablu
var sourceCount = db.CLOUD_PROPERTIES.countDocuments({})
if (sourceCount > 0) {
    print("Found " + sourceCount + " documents in parablu.CLOUD_PROPERTIES")
    var data = db.CLOUD_PROPERTIES.find().toArray()
}
use parablu001
if (sourceCount > 0) {
    var bulkOps = data.map(function(doc) {
        return {
            replaceOne: {
                filter: { _id: doc._id },
                replacement: doc,
                upsert: true
            }
        }
    })
    var result = db.CLOUD_PROPERTIES.bulkWrite(bulkOps)
    print("Upserted " + (result.upsertedCount + result.modifiedCount) + " documents to parablu001.CLOUD_PROPERTIES")
    print("Collection successfully copied from parablu to parablu001 (original preserved)")
} else {
    print("No CLOUD_PROPERTIES collection found in parablu database - nothing to copy")
}
EOF

    echo "CLOUD_PROPERTIES collection copy operation completed."

    # ==========================================
    # Extract DNS credentials from MongoDB
    # ==========================================
    echo "Extracting DNS credentials from MongoDB..."

    cat > getdnsdetails.js <<'EOF'
use parablu

var usernameval = db.CLOUD_PROPERTIES.findOne({}, { _id: 0, dnsUserName: 1 });
print("DNS_USERNAME=" + (usernameval && usernameval.dnsUserName));

var passwordval = db.CLOUD_PROPERTIES.findOne({}, { _id: 0, dnsPassword: 1 });
print("DNS_PASSWORD=" + (passwordval && passwordval.dnsPassword));
EOF

    sudo mongo --quiet localhost:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" \
        < getdnsdetails.js > getdnsdetails

    # Log the MongoDB command execution
    echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] MongoDB getdnsdetails.js executed" >> "$LOG_FILE"

    DNS_USERNAME=$(grep "DNS_USERNAME=" getdnsdetails | cut -d= -f2 | tr -d '[:space:]')
    DNS_PASSWORD=$(grep "DNS_PASSWORD=" getdnsdetails | cut -d= -f2 | tr -d '[:space:]')

    echo "Extracted DNS_USERNAME: $DNS_USERNAME" >> "$LOG_FILE"
    echo "Extracted DNS_PASSWORD: [REDACTED]" >> "$LOG_FILE"

    # Clean up temporary file
    log_exec rm -f getdnsdetails.js getdnsdetails

    # ==========================================
    # IDP Migration: Check and Run UpdateIDPSettings.jar
    # ==========================================
    echo "Checking IDENTITY_PROVIDER_SETTINGS collection..."

    cat > check_idp_collection.js << 'EOF'
use parablu001
var count = db.IDENTITY_PROVIDER_SETTINGS.find().count();
print("IDP_COUNT=" + count);
EOF

    sudo mongo --quiet localhost:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" \
        < check_idp_collection.js > check_idp_collection

    # Log the MongoDB command execution
    echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] MongoDB check_idp_collection.js executed" >> "$LOG_FILE"

    IDP_COUNT=$(grep "IDP_COUNT=" check_idp_collection | cut -d= -f2 | tr -d '[:space:]')

    if [ "$IDP_COUNT" -eq 0 ]; then
        echo "IDENTITY_PROVIDER_SETTINGS collection not found. Running UpdateIDPSettings.jar..."

        # Create temporary directory for JAR execution
        TEMP_DIR="/tmp/idp_update"
        log_exec mkdir -p "$TEMP_DIR"
        cd "$TEMP_DIR"

        # Download the JAR file and config
        JAR_URL="https://dns.parablu.com/parablu_installables/release/PRE_POST/2.6.3/post-commands/UpdateIDPSettings.jar"
        CONFIG_URL="https://dns.parablu.com/parablu_installables/release/PRE_POST/2.6.3/post-commands/config.txt"

        echo "Downloading UpdateIDPSettings.jar..."
        log_exec wget --user="${DNS_USERNAME}" --password="${DNS_PASSWORD}" \
            --no-check-certificate \
            -O "UpdateIDPSettings.jar" \
            "$JAR_URL"

        if [ $? -ne 0 ] || [ ! -f "UpdateIDPSettings.jar" ] || [ ! -s "UpdateIDPSettings.jar" ]; then
            echo "ERROR: Failed to download UpdateIDPSettings.jar"
            cd -
            log_exec rm -rf "$TEMP_DIR"
        else
            echo "Downloading config.txt..."
            log_exec wget --user="${DNS_USERNAME}" --password="${DNS_PASSWORD}" \
                --no-check-certificate \
                -O "config.txt" \
                "$CONFIG_URL"

            if [ $? -ne 0 ] || [ ! -f "config.txt" ] || [ ! -s "config.txt" ]; then
                echo "ERROR: Failed to download config.txt"
                cd -
                log_exec rm -rf "$TEMP_DIR"
            else
                echo "Files downloaded successfully. Executing UpdateIDPSettings.jar..."

                # Execute the JAR with config parameter
                java -jar UpdateIDPSettings.jar config.txt >> "$LOG_FILE" 2>&1

                JAR_EXIT_CODE=$?

                if [ $JAR_EXIT_CODE -eq 0 ]; then
                    echo "UpdateIDPSettings.jar executed successfully"
                else
                    echo "ERROR: UpdateIDPSettings.jar execution failed with exit code: $JAR_EXIT_CODE"
                fi

                # Clean up
                cd -
                log_exec rm -rf "$TEMP_DIR"

                echo "UpdateIDPSettings.jar execution completed."
            fi
        fi
    else
        echo "IDENTITY_PROVIDER_SETTINGS collection already exists (count: $IDP_COUNT). Skipping IDP migration."
    fi

    # Clean up temporary file
    log_exec rm -f check_idp_collection.js check_idp_collection

    # ==========================================
    # TENANCY TYPE SELECTION
    # ==========================================
    echo ""
    echo "=== Tenancy Setup Selection ==="

    while true; do
        echo "Is this a Single Tenancy or Multi Tenancy setup?"
        echo "1. Single Tenancy Setup"
        echo "2. Multi Tenancy Setup"
        read -p "Please select (1 or 2): " TENANCY_TYPE

        if [ "$TENANCY_TYPE" == "1" ]; then
            echo "You selected: Single Tenancy Setup"
            echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Selected: Single Tenancy Setup" >> "$LOG_FILE"
            echo ""
            echo "Single Tenancy setup is already configured. Skipping folder movement operations."
            echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Single Tenancy setup already done - skipping folder operations" >> "$LOG_FILE"
            break

        elif [ "$TENANCY_TYPE" == "2" ]; then
            echo "You selected: Multi Tenancy Setup"
            echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Selected: Multi Tenancy Setup" >> "$LOG_FILE"

            # ==========================================
            # Move BluKryptBuilder, ParacloudSearch, and paracloud to Home Directory
            # ==========================================
            echo "=== Moving BluKryptBuilder, ParacloudSearch, and paracloud to Home Directory ==="

            WEBAPPS_PCB1_DIR="/var/lib/tomcat-pcb1/webapps"
            PCB1_TARGETS=("BluKryptBuilder" "ParacloudSearch" "paracloud")

            echo "Starting cleanup in: $WEBAPPS_PCB1_DIR"
            cd "$WEBAPPS_PCB1_DIR" || { echo "Directory not found: $WEBAPPS_PCB1_DIR"; exit 1; }

            for dir in "${PCB1_TARGETS[@]}"; do
                if [ -d "$dir" ]; then
                    echo "Moving directory: $dir"
                    # Delete destination if it exists
                    if [ -d "/home/ubuntu/$dir" ]; then
                        echo "Removing existing directory at destination: /home/ubuntu/$dir"
                        log_exec sudo rm -rf "/home/ubuntu/$dir"
                    fi
                    log_exec sudo mv "$dir" /home/ubuntu/
                else
                    echo "Directory not found, skipping: $dir"
                fi
            done

            echo "BluKryptBuilder, ParacloudSearch, and paracloud moved successfully."


            # ==========================================
            # Move BluKryptJob, MSJob and paracloudjob to Home Directory
            # ==========================================
            echo "=== Moving BluKryptJob, MSJob and paracloudjob to Home Directory ==="

            WEBAPPS_JOB1_DIR="/var/lib/tomcat-job1/webapps"
            JOB1_TARGETS=("BluKryptJob" "MSJob" "paracloudjob")

            echo "Starting cleanup in: $WEBAPPS_JOB1_DIR"
            cd "$WEBAPPS_JOB1_DIR" || { echo "Directory not found: $WEBAPPS_JOB1_DIR"; exit 1; }

            for dir in "${JOB1_TARGETS[@]}"; do
                if [ -d "$dir" ]; then
                    echo "Moving directory: $dir"
                    # Delete destination if it exists
                    if [ -d "/home/ubuntu/$dir" ]; then
                        echo "Removing existing directory at destination: /home/ubuntu/$dir"
                        log_exec sudo rm -rf "/home/ubuntu/$dir"
                    fi
                    log_exec sudo mv "$dir" /home/ubuntu/
                else
                    echo "Directory not found, skipping: $dir"
                fi
            done

            echo "BluKryptJob, MSJob and paracloudjob moved successfully."
            break

        else
            echo "Invalid selection. Please choose 1 or 2."
            echo ""
        fi
    done

    # ==========================================
    # Check if db_parablu exists in credential files
    # ==========================================
    echo ""
    echo "=== Checking for existing db_parablu configuration ==="

    PB_CREDS_FILES=(
        "/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-job1/webapps/paracloudjob/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-pcb1/webapps/paramail/WEB-INF/classes/pb-credential.properties"
        "/var/lib/tomcat-pcb1/webapps/support/WEB-INF/classes/pb-credential.properties"
    )

    # Array to store files that need updating
    FILES_TO_UPDATE=()

    for PB_CREDS_FILE in "${PB_CREDS_FILES[@]}"; do
        if [ -f "$PB_CREDS_FILE" ]; then
            if grep -q "^db_parablu=" "$PB_CREDS_FILE"; then
                echo "db_parablu already exists in: $PB_CREDS_FILE - skipping"
                echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] db_parablu found in $PB_CREDS_FILE - skipping" >> "$LOG_FILE"
            else
                echo "db_parablu NOT found in: $PB_CREDS_FILE - will update"
                echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] db_parablu not found in $PB_CREDS_FILE - marking for update" >> "$LOG_FILE"
                FILES_TO_UPDATE+=("$PB_CREDS_FILE")
            fi
        else
            echo "Warning: File $PB_CREDS_FILE does not exist - skipping."
            echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] File not found: $PB_CREDS_FILE" >> "$LOG_FILE"
        fi
    done

    if [ ${#FILES_TO_UPDATE[@]} -eq 0 ]; then
        echo "All credential files already have db_parablu configured. Skipping MongoDB configuration."
        echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] All files have db_parablu - skipping MongoDB configuration" >> "$LOG_FILE"
    else
        echo "Found ${#FILES_TO_UPDATE[@]} file(s) that need db_parablu configuration."
        echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] ${#FILES_TO_UPDATE[@]} files need db_parablu configuration" >> "$LOG_FILE"

        # ==========================================
        # MongoDB Configuration Selection (Common for Both Single and Multi Tenancy)
        # ==========================================
        echo ""
        echo "=== MongoDB Configuration ==="

        # Loop until valid setup choice is selected
        while true; do
            echo "Is this setup Clustered or Non-Clustered?"
            echo "1. Non-Clustered Setup"
            echo "2. Clustered Setup"
            read -p "Please select (1 or 2): " setup_choice

            case $setup_choice in
                1)
                    echo "Configuring for Non-Clustered Setup..."
                    echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Selected: Non-Clustered Setup" >> "$LOG_FILE"

                    # Ask for environment type (same as clustered setup)
                    while true; do
                        echo "Select the environment:"
                        echo "1. Dev"
                        echo "2. QA"
                        echo "3. Stage"
                        echo "4. Prod"
                        read -p "Please select (1, 2, 3 or 4): " env_choice

                        case $env_choice in
                            1)
                                ENV_TYPE="dev"
                                break
                                ;;
                            2)
                                ENV_TYPE="qa"
                                break
                                ;;
                            3)
                                ENV_TYPE="stage"
                                break
                                ;;
                            4)
                                ENV_TYPE="prod"
                                break
                                ;;
                            *)
                                echo "Invalid selection. Please choose 1, 2, 3 or 4."
                                echo ""
                                ;;
                        esac
                    done

                    COMMENT="# MongoDB Configuration - Non-Clustered Setup"
                    DB_PARABLU_VALUE="mongodb://\$PB{db_user}:\$PB{db_password}@${BLUVAULT_IP}:48765,${BLUVAULT_IP}:48765,${BLUVAULT_IP}:48765/"

                    # Update only files that don't have db_parablu
                    for PB_CREDS_FILE in "${FILES_TO_UPDATE[@]}"; do
                        echo "Updating: $PB_CREDS_FILE"
                        log_exec sed -i '/^db_parablu=/d' "$PB_CREDS_FILE"
                        log_exec sed -i '/^# MongoDB Configuration/d' "$PB_CREDS_FILE"

                        {
                            echo "$COMMENT"
                            echo "db_parablu=$DB_PARABLU_VALUE"
                        } >> "$PB_CREDS_FILE"

                        echo "Updated $PB_CREDS_FILE with db_parablu configuration"
                        echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Updated $PB_CREDS_FILE with db_parablu" >> "$LOG_FILE"
                    done

                    echo "Non-Clustered MongoDB configuration completed successfully."
                    echo "Environment: $ENV_TYPE"
                    echo "MongoDB Host: $BLUVAULT_IP"
                    echo "Updated ${#FILES_TO_UPDATE[@]} file(s)"
                    break
                    ;;

                2)
                    echo "Configuring for Clustered Setup..."
                    echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Selected: Clustered Setup" >> "$LOG_FILE"

                    # Ask for environment type
                    while true; do
                        echo "Select the environment:"
                        echo "1. Dev"
                        echo "2. QA"
                        echo "3. Stage"
                        echo "4. Prod"
                        read -p "Please select (1, 2, 3 or 4): " env_choice

                        case $env_choice in
                            1)
                                ENV_TYPE="dev"
                                REPLICA_SET="nonprod"
                                MONGO_HOST="mydbops-nonprod-dev.parablu.com"
                                break
                                ;;
                            2)
                                ENV_TYPE="qa"
                                REPLICA_SET="qanonprod"
                                MONGO_HOST="mydbops-nonprod-qa2.parablu.com"
                                break
                                ;;
                            3)
                                ENV_TYPE="stage"
                                REPLICA_SET="dbstageuse"
                                MONGO_HOST="db-stage-use.crashplan.com"
                                break
                                ;;
                            4)
                                ENV_TYPE="prod"

                                # Ask for region selection
                                while true; do
                                    echo "Select the region:"
                                    echo "1. Central India"
                                    echo "2. East US"
                                    echo "3. Germany"
                                    echo "4. UAE North"
                                    read -p "Please select (1, 2, 3, or 4): " region_choice

                                    case $region_choice in
                                        1)
                                            REPLICA_SET="dbprodin1"
                                            MONGO_HOST="db-prod-in.crashplan.com"
                                            echo "Selected: Central India"
                                            break
                                            ;;
                                        2)
                                            REPLICA_SET="dbproduse"
                                            MONGO_HOST="db-prod-use.crashplan.com"
                                            echo "Selected: East US"
                                            break
                                            ;;
                                        3)
                                            REPLICA_SET="dbprodffm1"
                                            MONGO_HOST="db-prod-ffm.crashplan.com"
                                            echo "Selected: Germany"
                                            break
                                            ;;
                                        4)
                                            REPLICA_SET="dbproduae1"
                                            MONGO_HOST="db-prod-uae.crashplan.com"
                                            echo "Selected: UAE North"
                                            break
                                            ;;
                                        *)
                                            echo "Invalid selection. Please choose 1, 2, 3, or 4."
                                            echo ""
                                            ;;
                                    esac
                                done
                                break
                                ;;
                            *)
                                echo "Invalid selection. Please choose 1, 2, 3 or 4."
                                echo ""
                                ;;
                        esac
                    done

                    COMMENT="# MongoDB Configuration - Clustered Setup"
                    DB_PARABLU_VALUE="mongodb+srv://\$PB{db_user}:\$PB{db_password}@${MONGO_HOST}/?replicaSet=${REPLICA_SET}&authSource=admin&tls=false"

                    # Update only files that don't have db_parablu
                    for PB_CREDS_FILE in "${FILES_TO_UPDATE[@]}"; do
                        echo "Updating: $PB_CREDS_FILE"
                        log_exec sed -i '/^db_parablu=/d' "$PB_CREDS_FILE"
                        log_exec sed -i '/^# MongoDB Configuration/d' "$PB_CREDS_FILE"

                        {
                            echo "$COMMENT"
                            echo "db_parablu=$DB_PARABLU_VALUE"
                        } >> "$PB_CREDS_FILE"

                        echo "Updated $PB_CREDS_FILE with db_parablu configuration"
                        echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] Updated $PB_CREDS_FILE with db_parablu" >> "$LOG_FILE"
                    done

                    echo "Clustered MongoDB configuration completed successfully."
                    echo "Environment: $ENV_TYPE"
                    echo "ReplicaSet: $REPLICA_SET"
                    echo "MongoDB Host: $MONGO_HOST"
                    echo "Updated ${#FILES_TO_UPDATE[@]} file(s)"
                    break
                    ;;

                *)
                    echo "Invalid selection. Please choose 1 or 2."
                    echo ""
                    ;;
            esac
        done

        echo "MongoDB configuration completed."
    fi
fi
