# 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" == "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."

    # ==========================================
    # 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

    # Setup type selection
    while true; do
        echo ""
        echo "Setup type:"
        echo "1. Single Tenancy Setup"
        echo "2. Multi Tenancy Setup"
        read -p "Please select (1 or 2): " TENANT_TYPE
        
        if [ "$TENANT_TYPE" == "1" ]; then
            # Single Tenancy Setup
            echo "You selected: Single Tenancy Setup"
            echo "All Single Tenancy configurations are now handled via the main installer. No further action required here."
            break

        # Multi Tenancy Setup
        elif [ "$TENANT_TYPE" == "2" ]; then
            echo "You selected: Multi Tenancy Setup"

            # ==========================================
            # 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"
                    log_exec sudo mv "$dir" /home/parablu
                else
                    echo "Directory not found, skipping: $dir"
                fi
            done

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

            # ==========================================
            # Update domain configuration from parablu_config.sh
            # ==========================================
            echo "=== Updating domain configuration from parablu_config.sh ==="

            if [ -z "$BLUVAULT_IP" ]; then
                echo "Error: BLUVAULT_IP not set. Make sure parablu_config.sh is sourced."
                echo "BLUVAULT_IP not found in config file" >> "$LOG_FILE"
            else
                echo "Extracted BLUVAULT_IP: $BLUVAULT_IP"
                echo "Domain extracted: $BLUVAULT_IP" >> "$LOG_FILE"

                # Define credential files for paralite, paramail, and support
                CRED_FILES=(
                    "/var/lib/tomcat-pcb1/webapps/paralite/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"
                )

                # Update pb-credential.properties files
                for CRED_FILE in "${CRED_FILES[@]}"; do
                    if [ -f "$CRED_FILE" ]; then
                        echo "Processing: $CRED_FILE"

                        # Update db_host entries
                        log_exec sed -i "s/^db_host=.*/db_host=$BLUVAULT_IP/" "$CRED_FILE"
                        log_exec sed -i "s/^db_host\([0-9]\+\)=.*/db_host\1=$BLUVAULT_IP/" "$CRED_FILE"

                        echo "Updated db_host entries in $CRED_FILE" >> "$LOG_FILE"
                    else
                        echo "Warning: File $CRED_FILE not found - skipping."
                    fi
                done

                # Update pb-cloudproperty.properties file (only in paralite)
                CLOUD_FILE="/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/pb-cloudproperty.properties"
                if [ -f "$CLOUD_FILE" ]; then
                    echo "Processing: $CLOUD_FILE"
                    log_exec sed -i "s/^componentName=.*/componentName=$BLUVAULT_IP/" "$CLOUD_FILE"

                    echo "Updated componentName in $CLOUD_FILE" >> "$LOG_FILE"
                    echo "Updated componentName to: $BLUVAULT_IP"
                else
                    echo "Warning: File $CLOUD_FILE not found - skipping."
                fi

                echo "Domain configuration update completed successfully!"
                echo "Domain changed to: $BLUVAULT_IP"

                # ==========================================
                # 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"
                        log_exec sudo mv "$dir" /home/parablu
                    else
                        echo "Directory not found, skipping: $dir"
                    fi
                done

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

            # ==========================================
            # Configure Cron Jobs for Multi Tenancy Setup
            # ==========================================
            echo "=== Configuring Cron Jobs for Root User ==="

            # Backup existing crontab
            CRON_BACKUP="/tmp/crontab_backup_$(date +%Y%m%d_%H%M%S).txt"
            crontab -l > "$CRON_BACKUP" 2>/dev/null
            if [ $? -eq 0 ]; then
                echo "Existing crontab backed up to: $CRON_BACKUP"
                echo "Crontab backed up to: $CRON_BACKUP" >> "$LOG_FILE"
            else
                echo "No existing crontab found or user has no crontab."
            fi

            # Create new crontab content
            cat > /tmp/new_crontab.txt << 'CRON_EOF'
@reboot (echo "---- $(date) ----" >> /parablu/log/reboot-apache4.log; mkdir -p /var/run/apache4 >> /parablu/log/reboot-apache4.log 2>&1)
@reboot sleep 60 && cd /parablu-scripts/Installable/scripts/ && echo 'y' | bash service-parablu.sh start >> /parablu/cronreboot.log 2>&1
*/5 * * * * cd /parablu-scripts/Installable/scripts && ./pblicenserestart.sh >> /parablu/pblicenserestart.log 2>&1
*/5 * * * * cd /parablu-scripts/Installable/scripts/health_check && ./diskmonitor.sh >> /parablu/log/diskmonitor.log 2>&1
5 3 * * * cd /parablu-scripts/Installable/scripts/health_check && ./diskutil.sh
CRON_EOF

            # Install new crontab
            log_exec crontab /tmp/new_crontab.txt

            if [ $? -eq 0 ]; then
                echo "Crontab configured successfully for Multi Tenancy Setup"
                echo "New crontab entries:"
                crontab -l
                echo "Crontab configured successfully" >> "$LOG_FILE"
            else
                echo "ERROR: Failed to configure crontab"
                echo "ERROR: Crontab configuration failed" >> "$LOG_FILE"
                
                # Restore backup if installation failed
                if [ -f "$CRON_BACKUP" ]; then
                    echo "Restoring previous crontab from backup..."
                    crontab "$CRON_BACKUP"
                fi
            fi

            # Clean up temporary file
            log_exec rm -f /tmp/new_crontab.txt

            echo "Cron job configuration completed."

            # ==========================================
            # Remove MongoDB for Multi Tenancy Setup
            # ==========================================
            echo "=== Checking and Removing MongoDB for Multi Tenancy Setup ==="

            # Check if MongoDB is installed
            MONGO_INSTALLED=false

            if command -v mongod &> /dev/null; then
                echo "MongoDB executable found."
                MONGO_INSTALLED=true
            elif dpkg -l | grep -q mongodb-org; then
                echo "MongoDB package found via dpkg."
                MONGO_INSTALLED=true
            elif systemctl list-units --full -all | grep -q mongod.service; then
                echo "MongoDB service found."
                MONGO_INSTALLED=true
            fi

            if [ "$MONGO_INSTALLED" = true ]; then
                echo "MongoDB is installed. Proceeding with removal..."
                echo "MongoDB removal started at $(date)" >> "$LOG_FILE"

                # Stop MongoDB service
                echo "Stopping MongoDB service..."
                if systemctl is-active --quiet mongod; then
                    log_exec systemctl stop mongod
                    echo "MongoDB service stopped."
                else
                    echo "MongoDB service is not running."
                fi

                # Disable MongoDB service
                echo "Disabling MongoDB service..."
                if systemctl is-enabled --quiet mongod 2>/dev/null; then
                    log_exec systemctl disable mongod
                    echo "MongoDB service disabled."
                else
                    echo "MongoDB service is not enabled."
                fi

                # Remove MongoDB packages
                echo "Removing MongoDB packages..."
                log_exec apt-get purge -y mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-mongos mongodb-org-tools

                # Remove any remaining MongoDB packages
                echo "Removing any remaining MongoDB related packages..."
                log_exec apt-get autoremove -y

                # Remove MongoDB data directories
                echo "Removing MongoDB data directories..."
                if [ -d "/var/lib/mongodb" ]; then
                    log_exec rm -rf /var/lib/mongodb
                    echo "Removed /var/lib/mongodb"
                fi

                if [ -d "/var/lib/mongo" ]; then
                    log_exec rm -rf /var/lib/mongo
                    echo "Removed /var/lib/mongo"
                fi

                # Remove MongoDB log directory
                echo "Removing MongoDB log directory..."
                if [ -d "/var/log/mongodb" ]; then
                    log_exec rm -rf /var/log/mongodb
                    echo "Removed /var/log/mongodb"
                fi

                # Remove MongoDB configuration file
                echo "Removing MongoDB configuration file..."
                if [ -f "/etc/mongod.conf" ]; then
                    log_exec rm -f /etc/mongod.conf
                    echo "Removed /etc/mongod.conf"
                fi

                # Remove MongoDB systemd service file
                echo "Removing MongoDB systemd service file..."
                if [ -f "/lib/systemd/system/mongod.service" ]; then
                    log_exec rm -f /lib/systemd/system/mongod.service
                    echo "Removed /lib/systemd/system/mongod.service"
                fi

                if [ -f "/etc/systemd/system/mongod.service" ]; then
                    log_exec rm -f /etc/systemd/system/mongod.service
                    echo "Removed /etc/systemd/system/mongod.service"
                fi

                # Reload systemd daemon
                echo "Reloading systemd daemon..."
                log_exec systemctl daemon-reload

                # Remove MongoDB repository
                echo "Removing MongoDB repository..."
                if [ -f "/etc/apt/sources.list.d/mongodb-org.list" ]; then
                    log_exec rm -f /etc/apt/sources.list.d/mongodb-org.list
                    echo "Removed MongoDB repository file"
                fi

                if [ -f "/etc/apt/sources.list.d/mongodb-org-*.list" ]; then
                    log_exec rm -f /etc/apt/sources.list.d/mongodb-org-*.list
                    echo "Removed MongoDB repository files"
                fi

                # Remove MongoDB GPG key
                echo "Removing MongoDB GPG keys..."
                if [ -f "/usr/share/keyrings/mongodb-server-*.gpg" ]; then
                    log_exec rm -f /usr/share/keyrings/mongodb-server-*.gpg
                    echo "Removed MongoDB GPG keys"
                fi

                # Update package lists
                echo "Updating package lists..."
                log_exec apt-get update

                echo "MongoDB has been completely removed from the system."
                echo "MongoDB removal completed at $(date)" >> "$LOG_FILE"

                # Verify removal
                if ! command -v mongod &> /dev/null; then
                    echo "Verification: MongoDB executable not found. Removal successful."
                else
                    echo "Warning: MongoDB executable still found after removal attempt."
                fi

            else
                echo "MongoDB is not installed on this system. No removal needed."
                echo "MongoDB not found - skipping removal" >> "$LOG_FILE"
            fi

            echo "MongoDB removal check completed."

            # ==========================================
            # Configure Tomcat-pcb1 Memory Settings (12GB)
            # ==========================================
            echo "=== Configuring Tomcat-pcb1 Memory Settings ==="

            TOMCAT_PCB1_INIT="/etc/init.d/tomcat-pcb1"

            if [ -f "$TOMCAT_PCB1_INIT" ]; then
                echo "Found Tomcat-pcb1 init script: $TOMCAT_PCB1_INIT"

                # Backup the original file
                TOMCAT_BACKUP="${TOMCAT_PCB1_INIT}.backup_$(date +%Y%m%d_%H%M%S)"
                log_exec cp "$TOMCAT_PCB1_INIT" "$TOMCAT_BACKUP"
                echo "Backup created: $TOMCAT_BACKUP"
                echo "Tomcat-pcb1 init script backed up to: $TOMCAT_BACKUP" >> "$LOG_FILE"

                # Check if CATALINA_OPTS already exists in the file
                if grep -q "^export CATALINA_OPTS=" "$TOMCAT_PCB1_INIT"; then
                    echo "CATALINA_OPTS found. Updating existing configuration..."
                    
                    # Update existing CATALINA_OPTS to set 12GB memory
                    log_exec sed -i 's/^export CATALINA_OPTS=.*/export CATALINA_OPTS="-Xmx12086m"/' "$TOMCAT_PCB1_INIT"
                    echo "Updated existing CATALINA_OPTS to 12GB (12086m)" >> "$LOG_FILE"
                    
                elif grep -q "^CATALINA_OPTS=" "$TOMCAT_PCB1_INIT"; then
                    echo "CATALINA_OPTS found without export. Updating..."
                    
                    # Update CATALINA_OPTS and add export
                    log_exec sed -i 's/^CATALINA_OPTS=.*/export CATALINA_OPTS="-Xmx12086m"/' "$TOMCAT_PCB1_INIT"
                    echo "Updated CATALINA_OPTS to 12GB (12086m) with export" >> "$LOG_FILE"
                    
                else
                    echo "CATALINA_OPTS not found. Adding new configuration..."
                    
                    # Find the line number after the shebang and initial comments
                    # Add CATALINA_OPTS after the initial block of comments
                    log_exec sed -i '/^#!\/bin\/bash/a \\nexport CATALINA_OPTS="-Xmx12086m"' "$TOMCAT_PCB1_INIT"
                    echo "Added CATALINA_OPTS=12GB (12086m) to init script" >> "$LOG_FILE"
                fi

                echo "Tomcat-pcb1 memory configuration updated successfully."
                echo "Set CATALINA_OPTS to: -Xmx12086m (12GB)"

                # Verify the change
                if grep -q 'export CATALINA_OPTS="-Xmx12086m"' "$TOMCAT_PCB1_INIT"; then
                    echo "Verification: Memory setting confirmed in $TOMCAT_PCB1_INIT"
                else
                    echo "Warning: Unable to verify memory setting in $TOMCAT_PCB1_INIT"
                fi

                # Note about restart requirement
                echo ""
                echo "NOTE: Tomcat-pcb1 service needs to be restarted for changes to take effect."
                echo "Tomcat-pcb1 memory configured to 12GB - restart required" >> "$LOG_FILE"

            else
                echo "ERROR: Tomcat-pcb1 init script not found at $TOMCAT_PCB1_INIT"
                echo "ERROR: Tomcat-pcb1 init script not found" >> "$LOG_FILE"
            fi

            echo "Tomcat-pcb1 memory configuration completed."

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

    # ==========================================
    # 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..."
                
                # 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"
                            REPLICA_SET="dbproduse"
                            MONGO_HOST="db-prod-use.crashplan.com"
                            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}@${MONGO_HOST}:48765,${MONGO_HOST}:48765,${MONGO_HOST}:48765/"

                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 '/^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"
                done
                echo "Non-Clustered MongoDB configuration completed successfully."
                echo "Environment: $ENV_TYPE"
                echo "MongoDB Host: $MONGO_HOST"
                break
                ;;

            2)
                echo "Configuring for Clustered Setup..."

                # 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"
                            REPLICA_SET="dbproduse"
                            MONGO_HOST="db-prod-use.crashplan.com"
                            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"

                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 '/^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"
                done
                echo "Clustered MongoDB configuration completed successfully."
                echo "Environment: $ENV_TYPE"
                echo "ReplicaSet: $REPLICA_SET"
                echo "MongoDB Host: $MONGO_HOST"

                break
                ;;

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

    echo "MongoDB configuration completed."
fi
