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
                rm -rf /var/www/portal/*
                cp -r Portal_V2.zip /var/www/portal/
                cd /var/www/portal/
                        ##new portal extraction
                        unzip -oqq Portal_V2.zip
                        rm -rf Portal_V2.zip
                        chmod -R 755 *
                        chown -R www-data:www-data *
                cd -

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

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

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

        fi
fi

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

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

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

        cp -r /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-cloudproperty.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
        cp -r /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-credential.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
        service tomcat-pcb1 stop && service tomcat-job1 stop
        sleep 2s
        cd /var/lib/tomcat-pcb1/webapps/
        rm -rf paralite.war
        sleep 1s
        cd -
        sleep 2s
        service tomcat-pcb1 restart && 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 ' ')

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

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

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

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

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

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

	# 24-07-2025: [PC-324] Excel File
        chown -R tomcat:parablu bulkBlockUnblockDeleteSites.xlsx
        cp -rp bulkBlockUnblockDeleteSites.xlsx /parablu/bkpOverview/

	# 17-07-2025: [PC-314] and [PC-313]
        # Enable technical support access in CLOUD_PROPERTIES
        # Add 'Endpoint Restore AV Scan' to CLOUD_CUSTOMIZABLE_DETAILS
        # Set daysToKeepServerLogs to '7' in CLOUD_PROPERTIES

        echo "Applying CLOUD_PROPERTIES updates: techsupportaccess, Endpoint Restore AV Scan, and daysToKeepServerLogs..."

        cat > update_cloud_props_and_customizable_details.js << EOF
use parablu

db.CLOUD_PROPERTIES.updateMany({}, { \$set: { "techsupportaccess": true } })

db.CLOUD_CUSTOMIZABLE_DETAILS.updateOne(
  { "_id": ObjectId("58afc0c3fe617d5c50854d23") },
  { \$set: { "name": "Endpoint Restore AV Scan" } },
  { upsert: true }
)

db.CLOUD_PROPERTIES.updateMany({}, { \$set: { "daysToKeepServerLogs": "7" } })
EOF

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

        echo "CLOUD_PROPERTIES and CLOUD_CUSTOMIZABLE_DETAILS updated successfully."

        # 21-07-2025: [PC-306]
        # Configure serviceaccount.json

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

var cloudval = db.CLOUD.findOne({}, { _id: 0, cloudName: 1 });
print("CLOUD_NAME=" + (cloudval && cloudval.cloudName));

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));

use parablu001

var portalurlval = db.PRIVACY_GATEWAY.findOne({}, { _id: 0, "componentsProperties.paracloudUrl": 1 });
print("PORTAL_URL=" + (portalurlval && portalurlval.componentsProperties && portalurlval.componentsProperties.paracloudUrl));
EOF

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

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

        # Initial setup
        echo "Preparing installation directory..."

        # Create service account directory
        sudo mkdir -p /parablu/Serviceaccount

        # Download service account file
        sudo wget --user="${DNS_USERNAME}" --password="${DNS_PASSWORD}" -O /parablu/Serviceaccount/serviceaccount.json https://dns.parablu.com/parablu_installables/gmail/serviceaccount.json

        if [ ! -f "/parablu/Serviceaccount/serviceaccount.json" ] || [ ! -s "/parablu/Serviceaccount/serviceaccount.json" ]; then
            echo "ERROR: serviceaccount.json download failed or file is empty"
        else
            echo "serviceaccount.json downloaded successfully"
        fi

        # Set permissions and ownership
        sudo chmod -R 775 /parablu/Serviceaccount/
        sudo chown -R tomcat:tomcat /parablu/Serviceaccount/
        
	# Pinging ParaLite
        for i in {1..5}; do
            echo "Pinging paralite (Attempt $i)..."
            echo "URL: https://localhost/${CLOUD_NAME}/paralite/ping/"
            
            # Capture the HTTP status code
            STATUS_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
            --connect-timeout 60 --max-time 180 \
            -X GET "https://localhost/${CLOUD_NAME}/paralite/ping/" \
            -H "key: test" --insecure)

            echo "Status Code: $STATUS_CODE"

            if [ "$STATUS_CODE" -eq 400 ]; then
                echo "Paralite responded with 400 (acceptable), continuing..."
                break
            elif [ "$i" -eq 5 ]; then
                echo "ParaLite ping failed after 5 attempts."
            else
                echo "Attempt $i failed with status $STATUS_CODE. Retrying in 20 seconds..."
                sleep 60
            fi
        done

        # Service Account POST Command
        echo "Configuring Service Account for ${CLOUD_NAME}..."

        SUCCESS=false
        
	for i in {1..3}; do
            echo "Attempt $i to configure service account..."

            RESPONSE=$(curl -s -w "\nHTTP_STATUS_CODE:%{http_code}" \
                --connect-timeout 60 --max-time 180 \
                -X POST "https://localhost/paralite/cloud/${CLOUD_NAME}/save/serviceaccount/" \
                -H "internalCall: true" \
                -H "Content-Type: application/json" \
                -H "fileName: serviceaccount.json" \
                --insecure)

            HTTP_CODE=$(echo "$RESPONSE" | tail -n1 | cut -d: -f2)

            echo "Response Status Code: $HTTP_CODE"

            if [[ "$HTTP_CODE" == "200" ]]; then
                SUCCESS=true
                break
            else
                echo "Configuring Service Account failed on attempt $i with HTTP $HTTP_CODE"
                [ $i -eq 3 ] && echo "Giving up after 3 attempts." || sleep 30
            fi
        done

        if [ "$SUCCESS" = true ]; then
            echo "Successfully configured Service Account for ${CLOUD_NAME}."
        else
            echo "Failed to configure Service Account after 3 attempts."
        fi

	# 24-07-2025: [PC-301] Run ClamAV Script
        # Check if ClamAV is already installed
        if dpkg -l | grep -q clamav; then
            echo "ClamAV already installed. Applying configuration changes..."
            
            # Only change MaxFileSize to 4000M
            if grep -q "^MaxFileSize" /etc/clamav/clamd.conf; then
                sed -i 's/^MaxFileSize.*/MaxFileSize 4000M/' /etc/clamav/clamd.conf
            else
                echo "MaxFileSize 4000M" >> /etc/clamav/clamd.conf
            fi
            
            echo "ClamAV configuration completed."
        else
            echo "ClamAV not installed. Running installation script..."
            
            # Download and run the official ClamAV installation script
            CLAM_SCRIPT_URL="https://dns.parablu.com/parablu_installables/release/PRE_POST/2.5.5.0_vapt/post-commands/clam.sh"
            CLAM_SCRIPT_LOCAL="/tmp/clam_install.sh"
            
            echo "Downloading ClamAV script from $CLAM_SCRIPT_URL..."
            
            wget --user="${DNS_USERNAME}" --password="${DNS_PASSWORD}" \
                --no-check-certificate \
                -O "$CLAM_SCRIPT_LOCAL" \
                "$CLAM_SCRIPT_URL"
            
            if [ $? -eq 0 ] && [ -f "$CLAM_SCRIPT_LOCAL" ] && [ -s "$CLAM_SCRIPT_LOCAL" ]; then
                echo "Download successful. Running ClamAV installation script..."
                chmod +x "$CLAM_SCRIPT_LOCAL"
                bash "$CLAM_SCRIPT_LOCAL"
                rm -f "$CLAM_SCRIPT_LOCAL"
            else
                echo "Failed to download ClamAV installation script"
            fi
        fi

	# 24-07-2025: [PC-323] Apply JOB_CONFIG, REPORT_SCHEDULER, and CLOUD_PROPERTIES updates
        echo "Applying MongoDB updates for JOB_CONFIG, REPORT_SCHEDULER, and CLOUD_PROPERTIES..."

        cat > apply_mongo_updates.js << EOF
db = db.getSiblingDB("parablu001");

db.JOB_CONFIG.updateMany({}, { "\$set": { "job.deleteOldDownloadsJobCleaner": true } });

db.REPORT_SCHEDULER.updateOne(
    { "schedulerName": "deleteOldDownloadsJobTimer" },
    {
        "\$set": {
            "schedulerName": "deleteOldDownloadsJobTimer",
            "cronExprestion": "0 0 5 ? * *"
        }
    },
    { upsert: true }
);

db = db.getSiblingDB("parablu");

db.CLOUD_PROPERTIES.updateMany({}, { "\$set": { "noOfFoldersAllowedForZipDownload": 1000 } });
db.CLOUD_PROPERTIES.updateMany({}, { "\$set": { "noOfFilesAllowedForZipDownload": 10000 } });
db.CLOUD_PROPERTIES.updateMany({}, { "\$set": { "sizeAllowedForZipDownloadInMB": 25600 } });
db.CLOUD_PROPERTIES.updateMany({}, { "\$set": { "downloadRetentionDays": 14 } });
EOF

        # Run the script
        sudo mongo --quiet localhost:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" \
            < apply_mongo_updates.js

        echo "MongoDB updates completed."

	# 25-07-2025: [PC-309] Insert Blob Credential Details in BLOB_CREDENTIALS
        LOCATION=$(echo "$PORTAL_URL" | grep -oP 'portal-[^./]+')
        DECRYPTION_KEY="mK9pL2xQ7vN4wR8zE1"

        # Download encrypted file for this location
        wget --user="${DNS_USERNAME}" --password="${DNS_PASSWORD}" \
            -O /tmp/${LOCATION}.enc \
            https://dns.parablu.com/parablu_installables/release/PRE_POST/blob_credentials/${LOCATION}.enc

        # Decrypt credentials function
        decrypt_credentials() {
            local file="$1"
            local key="$2"
            openssl enc -aes-256-cbc -d -salt -pbkdf2 -iter 100000 -in "$file" -k "$key"
        }

        # Decrypt and extract values
	DECRYPTED_DATA=$(decrypt_credentials "/tmp/${LOCATION}.enc" "$DECRYPTION_KEY")
        IDENTITY=$(echo "$DECRYPTED_DATA" | grep "IDENTITY=" | cut -d= -f2)
        CREDENTIAL=$(echo "$DECRYPTED_DATA" | grep "CREDENTIAL=" | cut -d= -f2)

        # Clean up
        rm -f /tmp/${LOCATION}.enc

        # Use decrypted values in if-else
        if [ "$LOCATION" == "portal-in" ]; then
            BLOB_IDENTITY="$IDENTITY"
            BLOB_CREDENTIAL="$CREDENTIAL"
        elif [ "$LOCATION" == "portal-use" ]; then
            BLOB_IDENTITY="$IDENTITY"
            BLOB_CREDENTIAL="$CREDENTIAL"
        elif [ "$LOCATION" == "portal-me" ]; then
            BLOB_IDENTITY="$IDENTITY"
            BLOB_CREDENTIAL="$CREDENTIAL"
        elif [ "$LOCATION" == "portal-usw" ]; then
            BLOB_IDENTITY="$IDENTITY"
            BLOB_CREDENTIAL="$CREDENTIAL"
        else
            echo "Unknown location '$LOCATION', using India (portal-in) credentials as default..."
            
            # Download and decrypt India credentials as fallback
            wget --user="${DNS_USERNAME}" --password="${DNS_PASSWORD}" \
                -O /tmp/portal-in.enc \
                https://dns.parablu.com/parablu_installables/release/PRE_POST/blob_credentials/portal-in.enc
            
            INDIA_DECRYPTED_DATA=$(decrypt_credentials "/tmp/portal-in.enc" "$DECRYPTION_KEY")
            BLOB_IDENTITY=$(echo "$INDIA_DECRYPTED_DATA" | grep "IDENTITY=" | cut -d= -f2)
            BLOB_CREDENTIAL=$(echo "$INDIA_DECRYPTED_DATA" | grep "CREDENTIAL=" | cut -d= -f2)
            
            # Clean up
            rm -f /tmp/portal-in.enc
        fi

        # Insert BLOB_CREDENTIALS into MongoDB
        cat > insert_blob_credentials.js << EOF
use parablu

db.BLOB_CREDENTIALS.updateOne(
    { _id: ObjectId('686ba14a66f51160266aa80a') },
    {
        \$set: {
            cloudName: 'azureBlob',
            provider: 'azureblob',
            identity: '$BLOB_IDENTITY',
            credential: '$BLOB_CREDENTIAL',
            endPointUrl: '',
            containerName: '',
            blobTagName: 'APN\\/1.0 ParaBluInc/1.0 BluVault/2.5.4.6',
            _class: 'com.parablu.pcbd.domain.CloudCredentials'
        }
    },
    { upsert: true }
)
EOF

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

        echo "BLOB_CREDENTIALS inserted successfully."

fi

# List of JAR files to remove
JAR_FILES=(
    "google-api-client-1.22.0.jar"
    "google-http-client-1.22.0.jar"
    "google-oauth-client-1.22.0.jar"
    "google-http-client-jackson2-1.22.0.jar"
    "jackson-annotations-2.17.2.jar"
    "jackson-core-2.17.2.jar"
)

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "3 1" ]; then
    service tomcat-pcb1 stop && service tomcat-job1 stop
    sleep 2s

    # Remove files from tomcat-pcb1 repo
    cd /var/lib/tomcat-pcb1/repo
    for jar_file in "${JAR_FILES[@]}"; do
        if [ -f "$jar_file" ]; then
            echo "Removing $jar_file"
            rm -f "$jar_file"
        else
            echo "File $jar_file not found"
        fi
    done
    cd -

    sleep 1s

    # Remove files from tomcat-job1 repo
    cd /var/lib/tomcat-job1/repo
    for jar_file in "${JAR_FILES[@]}"; do
        if [ -f "$jar_file" ]; then
            echo "Removing $jar_file"
            rm -f "$jar_file"
        else
            echo "File $jar_file not found"
        fi
    done
    cd -

    sleep 2s

    service tomcat-pcb1 restart && service tomcat-job1 restart
fi

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

    SCHEDULER_FILE="/var/lib/tomcat-job1/webapps/MSJob/WEB-INF/classes/spring-config/scheduler-context.xml"
    dbport=$(grep port: /etc/mongod.conf)
    MONGODB_PORT=$(echo $dbport | sed -e 's/port://' | sed 's/"//g' | tr -d ' ')

    cat > checkmulti.js <<'EOF'
use parablu
var doc = db.CLOUD_PROPERTIES.findOne({}, { _id: 0, multiTenancy: 1 });
print("MULTI_TENANCY=" + (doc && doc.multiTenancy));
EOF

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

    MULTI_TEN=$(grep "MULTI_TENANCY=" checkmulti | tail -1 | cut -d= -f2 | tr -d '[:space:]')
    echo "$MULTI_TEN"

    if [ "$MULTI_TEN" == "true" ]; then
        echo "Disabling Job Triggers in Scheduler Context file"

	sed -i 's|^\s*<ref bean="odbAutoCrawlJobTrigger" />|<!--ref bean="odbAutoCrawlJobTrigger" />|' "$SCHEDULER_FILE"
        sed -i 's|^\s*<ref bean\s*=\s*"msStorageBackupJobTrigger" />|<ref bean ="msStorageBackupJobTrigger" /-->|' "$SCHEDULER_FILE"

        echo "Job Triggers in Scheduler Context file successfully disabled"
    fi
fi

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

#        cp -r /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-cloudproperty.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
#        cp -r /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-credential.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
#        service tomcat-pcb1 stop && service tomcat-job1 stop
#        sleep 2s
#        cd /var/lib/tomcat-pcb1/webapps/
#        rm -rf paralite.war
#        sleep 1s
#        cd -
#        sleep 2s
#        service tomcat-pcb1 restart && service tomcat-job1 restart
#fi
