#!/bin/bash

# Function to prompt for VM size
get_storage_destination() {
    while true; do
        read -p "Enter the Customer Destination Storage (1. OneDrive for Business(OD4B), 2. Azure Blob, 3. Google Drive, 4. Others(AWS / Local Storage / S3-Compatability / Wasabi / BackBlaze)): " stg_dest

        case $stg_dest in
        1)
            storage="OD4B"
            break
            ;;
        2)
            storage="Azure_Blob"
            break
            ;;
        3)
            storage="Google_Drive"
            break
            ;;
        4)
            storage="Others_Storage"
            break
            ;;
        *)
            echo "Invalid input. Please enter 1, 2, 3 or 4."
            ;;
        esac
    done
}

# Function to confirm user input
confirm_input() {
    while true; do
        read -p "$1 (y/n): " confirm
        case $confirm in
        [Yy]*) return 0 ;;
        [Nn]*) return 1 ;;
        *) echo "Please answer yes (y) or no (n)." ;;
        esac
    done
}

#while true; do

# Get Cloud Name
# Get the server hostname - which contian the cloudname - as part of the previous script.
# gethostname=$(hostname)

# # Remove the 'cust-' prefix
# if [[ $gethostname == cust-* ]]; then
#     newCloudName="${gethostname#cust-}"
# else
#     newCloudName="$gethostname"
# fi

# Resolve Server Public IP
resolveServerPublicIP=$5

#get the license file detail
isLicenseFileUploaded=$4

#get Validity number
newCloudValidity=$3

#get diskSize from js
dataDiskSizeGB=$2

# Get VM size
# get_storage_destination
storage=$1

# Print selected values
#echo "You have selected the following options:"
#echo "Location: $location"
#echo "Cloud Name: $newCloudName"
#echo "Destination Storage: $storage"

# Confirm the details
#    if confirm_input "Are these details correct?"; then
# Additional logic to use the variables can be added here

# For Linode, tenant will always be parablu
#if [ "$CLOUD_PROVIDER" == "linode" ]; then
    #tenant="parablu"
#else
tenant=$7
#fi

# 29-05-2025: Keeper changes
ADMIN_PORTAL_PASSWORD_HASH=${10}
VM_PASSWORD=${11}
IS_GMAIL_GDRIVE_SETUP=${12}

CATEGORY=${13}
API_GATEWAY_CLIENT_ID=${14}
API_GATEWAY_CLIENT_SECRET=${15}
AADCREDENTIALS_CLIENT_ID=${16}
AADCREDENTIALS_CLIENT_SECRET=${17}
TENANT_ID=${18}
API_GATEWAY_SCOPE=${19}

# SMTP Details
SMTP_USERNAME=${20}
SMTP_PASSWORD=${21}

RESOLVE_PIP_IP=${22}
IS_MIGRATION_SETUP=${23}
newCloudName=${24}
CLOUD_PROVIDER=${25}
DNS_USERNAME=${26}
DNS_PASSWORD=${27}
IDP_SETTING_CLIENT_ID=${28}
IDP_SETTING_CLIENT_SECRET=${29}
MS_APP_SETTING_CLIENT_ID=${30}
MS_APP_SETTING_CLIENT_SECRET=${31}

wget --user="$DNS_USERNAME" --password="$DNS_PASSWORD"

# 27-05-2025: [PC-214] Add Azure Storage Account details in CLOUD_CREDENTIALS if details are present ONLY
if [ "$CLOUD_PROVIDER" == "azure" ]; then
    AZURE_BLOB_IDENTITY=$8
    AZURE_BLOB_KEY=$9
else
    # For Linode, always set these as empty
    AZURE_BLOB_IDENTITY=""
    AZURE_BLOB_KEY=""
fi

#Define variables
if [[ "$tenant" == "parablu" ]]; then
    newParaCloudFQDN=$newCloudName".parablu.com"
elif [[ "$tenant" == "poc" ]]; then
    newParaCloudFQDN=$newCloudName".poc.crashplan.com"
elif [[ "$tenant" == "demo" ]]; then
    newParaCloudFQDN=$newCloudName".demo.crashplan.com"
elif [[ "$tenant" == "crashplan" ]]; then
    newParaCloudFQDN=$newCloudName".crashplan.com"
else
    echo "Something went wrong with generating Paracloud URL" >>"$log_file"
    exit 1
fi

log_file="postinstall_error.log"
echo "Proceeding with the following configuration..." >>"$log_file"

# https://portal-use.demo.crashplan.com/testdemo
FULL_URL=$6

newNGINXFQDN=$(echo "$FULL_URL" | sed -E 's|https://([^/]*).*|\1|')

echo "Using NGINX FQDN: $newNGINXFQDN" >>"$log_file"

#Fixed variable
oldCloudName="prodsuresh"
# portalPath="/var/www/portal/app/Core/"
portalPath="/var/www/portal/assets/"
portalPathJS="/var/www/portal/app/templates/default/js/angular/"
portalIndexHTMLPath="/var/www/portal/"
portalConfigFileJS="app.js"
# portalConfigFile="Config.php"
portalConfigFile="config.json"
portalIndexHTMLFile="index.html"
licenseJSFile="license.js"
# 19-05-2025: [PC-183] Make php session cookie secure
PHP_INI_FILE="/etc/php/8.1/apache2/php.ini"

MSJOBPATH="/var/lib/tomcat-job1/webapps/MSJob/WEB-INF/classes/"
BluKryptJobPATH="/var/lib/tomcat-job1/webapps/BluKryptJob/WEB-INF/classes/"
Leg_BluKryptJobPATH="/var/lib/tomcat-job1/webapps/LegacyBluKryptJob/WEB-INF/classes/"
ParacloudJobPATH="/var/lib/tomcat-job1/webapps/paracloudjob/WEB-INF/classes/"
PG_Properties="privacygateway.properties"
PB_CLOUD_CRE_Properties="pb-credential.properties"
PB_CLOUD_Properties="pb-cloudproperty.properties"
BluKryptpcb1PATH="/var/lib/tomcat-pcb1/webapps/BluKryptBuilder/WEB-INF/classes/"
ParacloudSearchpcb1PATH="/var/lib/tomcat-pcb1/webapps/ParacloudSearch/WEB-INF/classes/"
Paracloudpcb1PATH="/var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/"
Paralitepcb1PATH="/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/"
Paramailpcb1PATH="/var/lib/tomcat-pcb1/webapps/paramail/WEB-INF/classes/"
supportpcb1PATH="/var/lib/tomcat-pcb1/webapps/support/WEB-INF/classes/"
APACHE2_CONF_FILE_PATH="/etc/apache2/apache2.conf"
APACHE2_Default_FILE_PATH="/etc/apache2/sites-enabled/000-default.conf"
APACHE4_CONF_FILE_PATH="/etc/apache4/apache4.conf"
APACHE4_Default_FILE_PATH="/etc/apache4/sites-enabled/000-default.conf"
SCRIPT_PATH_CONFIG="/parablu-scripts/Installable/config/parablu_config.sh"
SCRIPT_PATH_COMPONENT="/parablu-scripts/Installable/config/parablu_component_config.sh"
PORT="48765"
RESOLV_CONFIG_FILE="/etc/resolv.conf"
LICENSE_JS_FILE_PATH="/parablu-scripts/Installable/scripts"
#End of Define variables

#hosts
# Get the current hostname
# variable_hostname=$(hostname)

# Check if the entry already exists in /etc/hosts
if grep -q "^127.0.0.1 localhost $newCloudName$" /etc/hosts; then
    echo "127.0.0.1 localhost $newCloudName already exists in /etc/hosts"
else
    # Update /etc/hosts
    sed -i "/^127\.0\.0\.1 localhost/s/$/ $newCloudName/" /etc/hosts
    echo "Updated /etc/hosts with 127.0.0.1 localhost $newCloudName"
fi

# Set hostname
sudo hostnamectl set-hostname $newCloudName

#Script config files:
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|" $SCRIPT_PATH_CONFIG
sed -i "s|prodsuresh|$newCloudName|" $SCRIPT_PATH_CONFIG
sed -i "s|portal-in.parablu.com|$newNGINXFQDN|" $SCRIPT_PATH_CONFIG

sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|" $SCRIPT_PATH_COMPONENT
sed -i "s|CUSTOMER_NAME=.*|CUSTOMER_NAME=$newCloudName|" $SCRIPT_PATH_COMPONENT

# 04-03-2025: Made Portal changes to reflect changes in config.json
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|" $portalPath/$portalConfigFile
sed -i "s|prodsuresh|$newCloudName|" $portalPath/$portalConfigFile
sed -i "s|portal-in.parablu.com|$newNGINXFQDN|" $portalPath/$portalConfigFile

# 19-01-2025: Change COMPONENT_NAME to .crashplan.com according to newParaCloudFQDN
if [[ "$newParaCloudFQDN" == *".crashplan.com" ]]; then
    sed -i 's|"COMPONENT_NAME": ".*"|"COMPONENT_NAME": ".crashplan.com"|' $portalPath/$portalConfigFile
fi

sed -i "s|prodsuresh|$newCloudName|" $portalIndexHTMLPath/$portalIndexHTMLFile

# 04-03-2025: Remove "prodsuresh"
sed -i 's/ prodsuresh//g' "/etc/hosts"

# 04-03-2025: Add Resolve Server Public IP
# Check if the nameserver entry already exists
if grep -q "^nameserver $resolveServerPublicIP$" "$RESOLV_CONFIG_FILE"; then
    echo "Nameserver $resolveServerPublicIP is already present in $RESOLV_CONFIG_FILE. No changes made."
else
    echo "Adding nameserver $resolveServerPublicIP to $RESOLV_CONFIG_FILE..."
    echo "nameserver $resolveServerPublicIP" | sed -i "1s/^nameserver [0-9.]\+/nameserver $resolveServerPublicIP/" $RESOLV_CONFIG_FILE >/dev/null
    echo "Nameserver added successfully."
fi

# 05-04-2025: Change the License.js file (prodsuresh to newCloudName)
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $LICENSE_JS_FILE_PATH/$licenseJSFile

# 04-03-2025: Make changes in /var/www/index.html (prodsuresh to newCloudName)
sed -i "s|prodsuresh|$newCloudName|g" /var/www/$portalIndexHTMLFile

#Apache2
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $APACHE2_Default_FILE_PATH
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $APACHE2_CONF_FILE_PATH

#Apache4
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $APACHE4_CONF_FILE_PATH
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $APACHE4_Default_FILE_PATH
sed -i "s|portal-in.parablu.com|$newNGINXFQDN|g" $APACHE4_Default_FILE_PATH

#Tomcat-job1
#MSJOB
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $MSJOBPATH/$PG_Properties

#BluKryptJob
sed -i "s|localdbhost=.*|localdbhost=$newParaCloudFQDN|" $BluKryptJobPATH/$PG_Properties
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $BluKryptJobPATH/$PG_Properties

#Leg_BluKryptJob
sed -i "s|localdbhost=.*|localdbhost=$newParaCloudFQDN|" $Leg_BluKryptJobPATH/$PG_Properties
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $Leg_BluKryptJobPATH/$PG_Properties

##paracloudjob
#sed -i "s|paracloudUrl=.*|paracloudUrl=https://$newParaCloudFQDN|" $ParacloudJobPATH/$PB_CLOUD_CRE_Properties
#sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $ParacloudJobPATH/$PB_CLOUD_Properties

#paracloudjob
sed -i "s|paracloudUrl=.*|paracloudUrl=https://$newParaCloudFQDN|" $ParacloudJobPATH/$PB_CLOUD_CRE_Properties
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $ParacloudJobPATH/$PB_CLOUD_Properties
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $ParacloudJobPATH/$PB_CLOUD_CRE_Properties

#Tomcat-pcb1
#BluKryptJob
sed -i "s|localdbhost=.*|localdbhost=$newParaCloudFQDN|" $BluKryptpcb1PATH/$PG_Properties
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $BluKryptpcb1PATH/$PG_Properties

#Paracloud Search
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $ParacloudSearchpcb1PATH/$PB_CLOUD_Properties

#Paracloud
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $Paracloudpcb1PATH/$PB_CLOUD_Properties

#Paralite
sed -i "s|componentName=.*|componentName=$newParaCloudFQDN|" $Paralitepcb1PATH/$PB_CLOUD_Properties

#paramail
sed -i "s|paracloudUrl=.*|paracloudUrl=https://$newParaCloudFQDN|" $Paramailpcb1PATH/$PB_CLOUD_CRE_Properties

#support
sed -i "s|paracloudUrl=.*|paracloudUrl=https://$newParaCloudFQDN|" $supportpcb1PATH/$PB_CLOUD_CRE_Properties

# 19-01-2026:
#Paracloud
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $Paracloudpcb1PATH/$PB_CLOUD_CRE_Properties

#Paralite
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $Paralitepcb1PATH/$PB_CLOUD_CRE_Properties

#paramail (already has paracloudUrl line, adding prodsuresh replacement)
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $Paramailpcb1PATH/$PB_CLOUD_CRE_Properties

#support (already has paracloudUrl line, adding prodsuresh replacement)
sed -i "s|prodsuresh.parablu.com|$newParaCloudFQDN|g" $supportpcb1PATH/$PB_CLOUD_CRE_Properties

#Storage type
if [ "$IS_MIGRATION_SETUP" == "true" ]; then
    echo "Migration setup detected. Skipping storage configuration." >>"$log_file"
else
    if [[ "$storage" == "OD4B" ]]; then
        echo "No change the selected storage is $OD4B" >>"$log_file"

    elif [[ "$storage" == "Azure_Blob" ]]; then

        wget --user="$DNS_USERNAME" --password="$DNS_PASSWORD" https://dns.parablu.com/parablu_installables/scripts/newdeploy/azureStorage.js

        if [[ -f "azureStorage.js" ]]; then
            sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <azureStorage.js >>"$log_file"
        else
            echo "No files present for Azure.js to execute" >>"$log_file"
            exit 1
        fi

    elif [[ "$storage" == "Google_Drive" ]]; then

        wget --user="$DNS_USERNAME" --password="$DNS_PASSWORD" https://dns.parablu.com/parablu_installables/scripts/newdeploy/googleStorage.js

        if [[ -f "googleStorage.js" ]]; then
            sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <googleStorage.js >>"$log_file"
        else
            echo "No files present for Google.js to execute" >>"$log_file"
            exit 1
        fi

    elif [[ "$storage" == "Others_Storage" ]]; then

        wget --user="$DNS_USERNAME" --password="$DNS_PASSWORD" https://dns.parablu.com/parablu_installables/scripts/newdeploy/otherStorage.js

        if [[ -f "otherStorage.js" ]]; then
            sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <otherStorage.js >>"$log_file"
        else
            echo "No files present for Other.js to execute" >>"$log_file"
            exit 1
        fi

    else
        echo "Storage is not Correct. Exiting script." >>"$log_file"
        echo "Storage= $storage" >>"$log_file"
        exit 1
    fi
fi

# 06-06-2025: Gmail related changes
if [ "$IS_GMAIL_GDRIVE_SETUP" == true ]; then
    echo "This is a Gmail and GDrive setup. Running required jobs..."

    SCHEDULER_FILE="/var/lib/tomcat-job1/webapps/MSJob/WEB-INF/classes/spring-config/scheduler-context.xml"
    
    # Check if environment parameter is provided
    if [ -z "$CATEGORY" ]; then
        echo "Error: Missing environment parameter. Usage: script.sh <ENVIRONMENT>"
        exit 1
    fi
    
    # Set gateway URL based on environment and tenant
    case "$CATEGORY" in
        "CUST")
            GATEWAY_URL="https://cust-apig-cp.poc.crashplan.com/api/v3"
            ;;
        "STAGE")
            GATEWAY_URL=" "
            ;;
        "POC")
            case "$tenant" in
                "parablu")
                    GATEWAY_URL="api2.parablu.com"
                    ;;
                "poc")
                    GATEWAY_URL=" "
                    ;;
                "demo")
                    GATEWAY_URL=" "
                    ;;
                *)
                    echo "Error: Invalid tenant for POC environment"
                    GATEWAY_URL=" "
                    ;;
            esac
            ;;
        "ENGG_DEV")
            case "$tenant" in
                "parablu")
                    GATEWAY_URL="https://qa-apig.parablu.com/api/v3"
                    ;;
                "poc")
                    GATEWAY_URL=" "
                    ;;
                "demo")
                    GATEWAY_URL=" "
                    ;;
                *)
                    echo "Error: Invalid tenant for ENGG_DEV environment"
                    GATEWAY_URL=" "
                    ;;
            esac
            ;;
        "ENGG_QA")
            case "$tenant" in
                "parablu")
                    GATEWAY_URL="https://qa-apig.parablu.com/api/v3"
                    ;;
                "poc")
                    GATEWAY_URL=" "
                    ;;
                "demo")
                    GATEWAY_URL=" "
                    ;;
                *)
                    echo "Error: Invalid tenant for ENGG_QA environment"
                    GATEWAY_URL=" "
                    ;;
            esac
            ;;
        "PROD")
            case "$tenant" in
                "parablu")
                    GATEWAY_URL=" "
                    ;;
                "poc")
                    GATEWAY_URL="https://cust-apig-cp.poc.crashplan.com/api/v3"
                    ;;
                "demo")
                    GATEWAY_URL=" "
                    ;;
                *)
                    echo "Error: Invalid tenant for PROD environment"
                    GATEWAY_URL=" "
                    ;;
            esac
            ;;
        "DEMO")
            case "$tenant" in
                "parablu")
                    GATEWAY_URL="api1.parablu.com"
                    ;;
                "poc")
                    GATEWAY_URL=" "
                    ;;
                "demo")
                    GATEWAY_URL="api1.parablu.com"
                    ;;
                *)
                    echo "Error: Invalid tenant for DEMO environment"
                    GATEWAY_URL=" "
                    ;;
            esac
            ;;
        *)
            echo "Error: Invalid environment. Supported environments: CUST, STAGE, POC, ENGG_DEV, ENGG_QA, PROD, DEMO"
            GATEWAY_URL=" "
            ;;
    esac
    
    echo "Using Client ID: $CLIENT_ID"
    echo "Using CATEGORY: $CATEGORY"
    echo "Using Gateway URL: $GATEWAY_URL"
    
    echo "Running MongoDB setup..."
    
    # Create the complete MongoDB script
    cat > dev_qa_post_commands << EOF
use parablu
db.CLOUD_PROPERTIES.update({},{\$set:{"multiTenancy": true}});
db.CLOUD_PROPERTIES.update({},{\$set:{"portalSSOEnable": true}});

db.CLOUD_CUSTOMIZABLE_DETAILS.updateOne(
  {"_id": ObjectId("58afc0c3fe617d5c50854d19")},
  {\$set: {"name": "GMAIL Backup Enabled"}},
  {upsert: true}
)
db.CLOUD_CUSTOMIZABLE_DETAILS.updateOne(
  {"_id": ObjectId("58afc0c3fe617d5c50854d20")},
  {\$set: {"name": "GDRIVE Backup Enabled"}},
  {upsert: true}
)

db.CLOUD_PROPERTIES.update({}, {"\$set": {"defaultGmailPolicyName": "GMAIL_STAGING_POLICY", "defaultGdrivePolicyName": "GOOGLE_DRIVE_STAGING_POLICY"}})

db.CLOUD_PROPERTIES.update({}, {"\$set": {"flipUsersTileGmail": true, "flipDevicesTileGmail": true, "flipTotalCompletedBackupsGmail": false, "activeUsersGmail": true, "activeDevicesGmail": true, "totalCompletedBackupsGmail": false}})
db.CLOUD_PROPERTIES.update({}, {"\$set": {"flipUsersTileGdrive": true, "flipDevicesTileGdrive": true, "flipTotalCompletedBackupsGdrive": false, "activeUsersGdrive": true, "activeDevicesGdrive": true, "totalCompletedBackupsGdrive": false}})

db.CLOUD_PROPERTIES.update({}, {"\$set": {"multiTenancy": true, "conversationalAI": true}})

use parablu001
db.CLOUD_PROPERTIES.update({},{\$set:{"multiTenancy": true, "conversationalAI": true}});
db.AADCREDENTIALS.updateOne(
  {"_id": ObjectId("6807977cccb94b5640b1419d")},
  {\$set: {
    "clientId": "$AADCREDENTIALS_CLIENT_ID",
    "clientIdForLogin": "",
    "secretKey": "$AADCREDENTIALS_CLIENT_SECRET",
    "tenentId": "",
    "redirectURI": "",
    "groupConfig": { "": "BOTH" },
    "endpointRedirectURI": "",
    "portalRedirectURI": "",
    "loginMode": "Google",
    "tenants": [],
    "advAADGroupMappingEnabled": false,
    "aadCredPrdouctPolicyList": [],
    "_class": "com.parablu.pcbd.domain.AADCredentials"
  }},
  {upsert: true}
)

db.API_GATEWAY_PROPERTIES.updateOne(
  {"clientId": "$API_GATEWAY_CLIENT_ID"},
  {\$set: {
    "clientId": "$API_GATEWAY_CLIENT_ID",
    "clientSecret": "$API_GATEWAY_CLIENT_SECRET",
    "gateWayUrl": "$GATEWAY_URL",
    "grantType": "client_credentials",
    "multiTenancy": true,
    "scope": "api://$API_GATEWAY_SCOPE/.default",
    "tenantId": "$TENANT_ID",
    "tokenEndpointTemplate": "https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"
  }},
  {upsert: true}
)

db.MS_APP_SETTING.updateOne(
  {"_id": ObjectId("6807977cccb94b5640b1419d")},
  {\$set: {
    "clientId": "$MS_APP_SETTING_CLIENT_ID",
    "clientSecret": "$MS_APP_SETTING_CLIENT_SECRET",
  }},
  {upsert: true}
)

db.IDP_SETTING.updateOne(
  {"_id": ObjectId("6807977cccb94b5640b1419d")},
  {\$set: {
    "clientId": "$IDP_SETTING_CLIENT_ID",
    "clientSecret": "$IDP_SETTING_CLIENT_SECRET",
  }},
  {upsert: true}
)

db.USER.update({"userName": "admin"}, {"\$set": {"gmailPolicyName": "GMAIL_STAGING_POLICY", "gdrivePolicyName": "GOOGLE_DRIVE_STAGING_POLICY"}})

db.GLOBAL_EXCLUDED_FOLDERS.updateOne(
  {"folderPath": "spam", "osType": "gmail"},
  {\$set: {
    "folderPath": "spam",
    "_class": "com.parablu.pcbd.domain.GLOBAL_EXCLUDED_FOLDERS",
    "osType": "gmail"
  }},
  {upsert: true}
)

db.createCollection("BACKUP_ATTEMPT")
db.BACKUP_ATTEMPT.createIndex({ "batchId": 1 })
db.BACKUP_ATTEMPT.createIndex({ "userName": 1 })
db.BACKUP_ATTEMPT.createIndex({ "deviceName": 1 })
db.BACKUP_ATTEMPT.createIndex({ "deviceUUID": 1 })

db.createCollection("BACKUP_BATCH")
db.BACKUP_BATCH.createIndex({ "userName": 1, "deviceName": 1, "jobType": 1 })
db.BACKUP_BATCH.createIndex({ "jobType": 1, "status": 1 })
db.BACKUP_BATCH.createIndex({ "jobType": 1, "status": 1, "deviceType": 1, "underProcessing": 1 })
db.BACKUP_BATCH.createIndex({ "userName": 1 })
db.BACKUP_BATCH.createIndex({ "deviceName": 1 })
db.BACKUP_BATCH.createIndex({ "deviceUUID": 1 })
db.BACKUP_BATCH.createIndex({ "deviceType": 1 })
db.BACKUP_BATCH.createIndex({ "underProcessing": 1 })
db.BACKUP_BATCH.createIndex({ "scanCompleted": 1 })

db.createCollection("CHUNK_DETAIL")
db.CHUNK_DETAIL.createIndex({ "md5": 1 })
db.CHUNK_DETAIL.createIndex({ "deviceUUID": 1 })

db.createCollection("DEVICE")
db.DEVICE.createIndex({ "deviceName": 1 })
db.DEVICE.createIndex({ "blocked": 1 })
db.DEVICE.createIndex({ "deviceUUID": 1 })
db.DEVICE.createIndex({ "userName": 1 })
db.DEVICE.createIndex({ "filesDelStorageIssue": 1 })

db.createCollection("DEVICE_BACKUP_OVERVIEW")
db.DEVICE_BACKUP_OVERVIEW.createIndex({ "userName": 1 })
db.DEVICE_BACKUP_OVERVIEW.createIndex({ "deviceUUID": 1 })

db.createCollection("RESTORE_PROGRESS_EVENT")
db.RESTORE_PROGRESS_EVENT.createIndex({ "userName": 1 })

db.createCollection("EXCHANGE_PREVIEW")
db.EXCHANGE_PREVIEW.createIndex({ "sentDate": 1 })
db.EXCHANGE_PREVIEW.createIndex({ "md5Hash": 1 })

db.MAIL_PREVIEW.createIndex({ "sentDate": 1 })
db.MAIL_PREVIEW.createIndex({ "md5Hash": 1 })

db.PORTAL_PROPERTIES.updateMany(
  {},
  {
    "\$set": {
      "componentsProperties.flipUsersTileGmail": true,
      "componentsProperties.flipDevicesTileGmail": true,
      "componentsProperties.flipTotalCompletedBackupsGmail": false,
      "componentsProperties.activeUsersGmail": true,
      "componentsProperties.activeDevicesGmail": true,
      "componentsProperties.totalCompletedBackupsGmail": false
    }
  }
)
db.PORTAL_PROPERTIES.updateMany(
  {},
  {
    "\$set": {
      "componentsProperties.flipUsersTileGdrive": true,
      "componentsProperties.flipDevicesTileGdrive": true,
      "componentsProperties.flipTotalCompletedBackupsGdrive": false,
      "componentsProperties.activeUsersGdrive": true,
      "componentsProperties.activeDevicesGdrive": true,
      "componentsProperties.totalCompletedBackupsGdrive": false
    }
  }
)

db.GSUITE_BACKUP_POLICY.updateOne(
  {"_id": ObjectId("67d13ad84c02487e81473864")},
  {\$set: {
    "_id": ObjectId("67d13ad84c02487e81473864"),
    "policyName": "GMAIL_STAGING_POLICY",
    "osType": "universal",
    "description": "",
    "emailsRestriction": {
      "createUser": "admins,readonlyadmins",
      "userDeleted": "admins,readonlyadmins",
      "userBlocked": "admins,readonlyadmins",
      "userLimitReached": "admins,readonlyadmins",
      "deviceDeleted": "admins,readonlyadmins",
      "deviceBlocked": "admins,readonlyadmins",
      "deviceDecoupled": "admins,readonlyadmins",
      "deviceLimitReached": "admins,readonlyadmins",
      "weeklyBkpreport": "admins,readonlyadmins",
      "firstBkpCompleted": "admins,readonlyadmins",
      "restoreInitiated": "admins,readonlyadmins",
      "storageLimitReached": "admins,readonlyadmins"
    },
    "menuOptions": {
      "open": true,
      "view": true,
      "versions": true,
      "share": false,
      "download": true,
      "restore": true
    },
    "endpointUiPreferences": [
      "BACKUP_FILES",
      "BACKUP_SETTINGS",
      "INTIATE_BACKUP",
      "STOP_BACKUP",
      "SUPPORT",
      "ABOUT",
      "SYSTRAYICON",
      "RESTORE",
      "REFRESH_BACKUP_POLICY",
      "PAUSE_BACKUP",
      "UPDATE_AGENT",
      "DECOUPLE",
      "EXIT"
    ],
    "endpointDisabledUiPreferences": [],
    "isShareEnabled": false,
    "isComplexPassword": true,
    "shareExpireDateEnable": true,
    "legalHoldEnabled": false,
    "isAllowDownload": false,
    "webBasedLogin": true,
    "policyRefresh": "4:00",
    "schedules": [ DBRef("SCHEDULE", ObjectId("57483affe4b0c27348270c38")) ],
    "maxVersions": 3,
    "maxFileSize": "1048576",
    "userSizeAllowed": 250,
    "msAppBluKrypt": "santhoshgmail.parablu.com",
    "backupFolders": [ DBRef("BACKUP_FOLDERS", ObjectId("5d47ffffe4b0e16df84e13dc")) ],
    "privacyGateways": [],
    "excludedFolders": [
      DBRef("EXCLUDED_FOLDERS", ObjectId("67cc277b098fb84b1e092020")),
      DBRef("EXCLUDED_FOLDERS", ObjectId("67cc277b098fb84b1e092021")),
      DBRef("EXCLUDED_FOLDERS", ObjectId("67ca921ee6a052bc45fdf394")),
      DBRef("EXCLUDED_FOLDERS", ObjectId("67ca921ee6a052bc45fdf395"))
    ],
    "inclusionFilter": [ DBRef("INCLUSION_FILTER", ObjectId("574c1f0ae4b04fe650d0e2bb")) ],
    "searchInclusionFilter": [ DBRef("INCLUSION_FILTER", ObjectId("574c1f0ae4b04fe650d0e2bb")) ],
    "isHighSecureShareEnabled": true,
    "searchAlgoForPg": "NEAREST",
    "isBlocked": false,
    "purgeDeletedFilesOlderThan": -1,
    "purgeDeletedMailsOlderThan": -1,
    "deletedMailsOlderThan": -1,
    "nwFromClientToPGMB": 10000,
    "dedup": "Global",
    "isContentIndexEnabled": true,
    "isInPlaceMailArchiveEnabled": true,
    "isContactsEnabled": false,
    "isTasksEnabled": false,
    "canAdminRestore": false,
    "downloadAgent": true,
    "noOfDaysToKeepDeletedFiles": NumberLong("-1"),
    "filterType": "inclusion",
    "searchFilterType": "inclusion",
    "canAdminDelete": false,
    "backupAllVersions": false,
    "noOfDaysToKeepUserDeviceNotActive": NumberLong("-1"),
    "filters": { "from": "", "subject": "", "to": "" },
    "noOfDevicesAllowed": 0,
    "active": false,
    "policyType": "Gmail",
    "compressionEnabled": true,
    "createMailLinkEnabled": false,
    "createLinkEnabled": false,
    "cpThresHoldFlagEnabled": false,
    "cpPurgeFilesOlderThanEnabled": false,
    "cpPurgeFilesSizeGTThanFlagEnabled": false,
    "threshholdLimit": NumberLong("80"),
    "purgeFilesOlderThan": 365,
    "purgeFilesSizeGTThan": 5,
    "isCalendarEnabled": false,
    "crawlVersions": 0,
    "lastModifiedTimestamp": NumberLong("1741765336701"),
    "_class": "com.parablu.pcbd.domain.GmailBackupPolicy"
  }},
  {upsert: true}
)

db.GSUITE_BACKUP_POLICY.updateOne(
  {"policyName": "GOOGLE_DRIVE_STAGING_POLICY"},
  {\$set: {
    "policyName": "GOOGLE_DRIVE_STAGING_POLICY",
    "osType": "universal",
    "description": "",
    "emailsRestriction": {
      "createUser": "admins,readonlyadmins",
      "userDeleted": "admins,readonlyadmins",
      "userBlocked": "admins,readonlyadmins",
      "userLimitReached": "admins,readonlyadmins",
      "deviceDeleted": "admins,readonlyadmins",
      "deviceBlocked": "admins,readonlyadmins",
      "deviceDecoupled": "admins,readonlyadmins",
      "deviceLimitReached": "admins,readonlyadmins",
      "weeklyBkpreport": "admins,readonlyadmins",
      "firstBkpCompleted": "admins,readonlyadmins",
      "restoreInitiated": "admins,readonlyadmins",
      "storageLimitReached": "admins,readonlyadmins"
    },
    "menuOptions": {
      "open": true,
      "view": true,
      "versions": true,
      "share": false,
      "download": true,
      "restore": true
    },
    "endpointUiPreferences": [
      "BACKUP_FILES",
      "BACKUP_SETTINGS",
      "INTIATE_BACKUP",
      "STOP_BACKUP",
      "SUPPORT",
      "ABOUT",
      "SYSTRAYICON",
      "RESTORE",
      "REFRESH_BACKUP_POLICY",
      "PAUSE_BACKUP",
      "UPDATE_AGENT",
      "DECOUPLE",
      "EXIT"
    ],
    "endpointDisabledUiPreferences": [],
    "isShareEnabled": false,
    "isComplexPassword": true,
    "shareExpireDateEnable": true,
    "legalHoldEnabled": false,
    "isAllowDownload": false,
    "webBasedLogin": true,
    "policyRefresh": "4:00",
    "schedules": [ DBRef("SCHEDULE", ObjectId("57483affe4b0c27348270c38")) ],
    "maxVersions": 3,
    "maxFileSize": "1048576",
    "userSizeAllowed": 250,
    "msAppBluKrypt": "santhoshgmail.parablu.com",
    "backupFolders": [ DBRef("BACKUP_FOLDERS", ObjectId("5d47ffffe4b0e16df84e13dc")) ],
    "privacyGateways": [],
    "excludedFolders": [
      DBRef("EXCLUDED_FOLDERS", ObjectId("67cc277b098fb84b1e092020")),
      DBRef("EXCLUDED_FOLDERS", ObjectId("67cc277b098fb84b1e092021")),
      DBRef("EXCLUDED_FOLDERS", ObjectId("67ca921ee6a052bc45fdf394")),
      DBRef("EXCLUDED_FOLDERS", ObjectId("67ca921ee6a052bc45fdf395"))
    ],
    "inclusionFilter": [ DBRef("INCLUSION_FILTER", ObjectId("574c1f0ae4b04fe650d0e2bb")) ],
    "searchInclusionFilter": [ DBRef("INCLUSION_FILTER", ObjectId("574c1f0ae4b04fe650d0e2bb")) ],
    "isHighSecureShareEnabled": true,
    "searchAlgoForPg": "NEAREST",
    "isBlocked": false,
    "purgeDeletedFilesOlderThan": -1,
    "purgeDeletedMailsOlderThan": -1,
    "deletedMailsOlderThan": -1,
    "nwFromClientToPGMB": 10000,
    "dedup": "Global",
    "isContentIndexEnabled": true,
    "isInPlaceMailArchiveEnabled": true,
    "isContactsEnabled": false,
    "isTasksEnabled": false,
    "canAdminRestore": false,
    "downloadAgent": true,
    "noOfDaysToKeepDeletedFiles": NumberLong("-1"),
    "filterType": "inclusion",
    "searchFilterType": "inclusion",
    "canAdminDelete": false,
    "backupAllVersions": false,
    "noOfDaysToKeepUserDeviceNotActive": NumberLong("-1"),
    "filters": { "from": "", "subject": "", "to": "" },
    "noOfDevicesAllowed": 0,
    "active": false,
    "policyType": "Google Drive",
    "compressionEnabled": true,
    "createMailLinkEnabled": false,
    "createLinkEnabled": false,
    "cpThresHoldFlagEnabled": false,
    "cpPurgeFilesOlderThanEnabled": false,
    "cpPurgeFilesSizeGTThanFlagEnabled": false,
    "threshholdLimit": NumberLong("80"),
    "purgeFilesOlderThan": 365,
    "purgeFilesSizeGTThan": 5,
    "isCalendarEnabled": false,
    "crawlVersions": 0,
    "lastModifiedTimestamp": NumberLong("1741765336701"),
    "_class": "com.parablu.pcbd.domain.GmailBackupPolicy"
  }},
  {upsert: true}
)
EOF
    
    # Run the MongoDB script
    echo "Executing DEV/QA Post Install MongoDB setup script..."
    sleep 3s
    if sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <dev_qa_post_commands >>"$log_file"; then
        echo "DEV/QA Post Install MongoDB setup completed successfully!"
    else
        echo "Error: DEV/QA Post Install MongoDB setup failed!"
        exit 1
    fi

    # File cleanup operations
    echo "Removing BluKryptBuilder"
    if [ -d "/var/lib/tomcat-pcb1/webapps/BluKryptBuilder" ]; then
        rm -rf /var/lib/tomcat-pcb1/webapps/BluKryptBuilder
        echo "BluKryptBuilder removed"
    else
        echo "BluKryptBuilder directory not found"
    fi

    echo "Removing google related files from tomcat-pcb1 folder"
    if [ -d "/var/lib/tomcat-pcb1/repo/" ]; then
        rm -rf /var/lib/tomcat-pcb1/repo/google*
        echo "Files successfully removed from tomcat-pcb1"
    else
        echo "tomcat-pcb1 repo directory not found"
    fi

    echo "Removing google related files from tomcat-job1 folder"
    if [ -d "/var/lib/tomcat-job1/repo/" ]; then
        rm -rf /var/lib/tomcat-job1/repo/google*
        echo "Files successfully removed from tomcat-job1"
    else
        echo "tomcat-job1 repo directory not found"
    fi

    # 10-07-2025: [PC-287] if multi tenancy is true then we have to disable the following jobs under blukrypt job folder.
    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"

else
    echo "This is NOT a Gmail and GDrive setup. Skipping required jobs..."
fi

# 19-05-2025: [PC-183] Make php session cookie secure
sed -i 's/;session.cookie_secure =/session.cookie_secure = 1/' "$PHP_INI_FILE"

sleep 2s
#
echo "Mongo entry changes" >>"$log_file"
echo "***** Changing cloud name **********"
echo 'use parablu
db.CLOUD.update({},{$set:{"cloudName" : "CLOUDPLACEHOLDER"}});' >cloud.js
sed -i "s|CLOUDPLACEHOLDER|$newCloudName|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "***** Changing cloud validity **********"
echo 'use parablu
db.CLOUD.update({},{$set:{"validityPeriod": VALIDITYPLACEHOLDER}});' >cloud.js
sed -i "s|VALIDITYPLACEHOLDER|$newCloudValidity|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "***** Changing SMTP CREDENTIALS **********"
SMTP_CREDENTIALS_UPDATE_COMMANDS=$( cat <<EOF
use parablu
db.SMTP_CREDENTIALS.update(
  {},
  {
    \$set: {
      "smtpHost" : "smtp.sendgrid.net",
      "smtpPwd" : "$SMTP_PASSWORD",
      "smtpUserName" : "$SMTP_USERNAME",
      "fromEmail" : "noreply@crashplan.com"
    }
  },
  {upsert: true}
)

use parablu001
db.SMTP_CREDENTIALS.update(
  {},
  {
    \$set: {
      "smtpHost" : "smtp.sendgrid.net",
      "smtpPwd" : "$SMTP_PASSWORD",
      "smtpUserName" : "$SMTP_USERNAME",
      "fromEmail" : "noreply@crashplan.com"
    }
  },
  {upsert: true}
)
EOF
)

# Execute the SMTP_CREDENTIALS_UPDATE_COMMANDS
echo "$SMTP_CREDENTIALS_UPDATE_COMMANDS" | sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" >>"$log_file"

# 14-07-2025: Update Resolve PIP IP based on POC and DEMO Tenant
if [[ "$tenant" == "poc" || "$tenant" == "demo" || "$tenant" == "crashplan" ]]; then
    if [[ -z "$RESOLVE_PIP_IP" ]]; then
        echo "Error: RESOLVE_PIP_IP is not set"
    fi

    sleep 2s
    echo "***** Updating Resolve PIP IP **********"

    RESOLVE_PIP_IP_UPDATE_COMMANDS=$(
        cat <<EOF
use parablu001

db.DNS_PROXY_SERVER.update(
  {},
  {
    \$set: {
      "publicIp": "$RESOLVE_PIP_IP"
    }
  },
  { upsert: true }
)
EOF
    )

    echo "$RESOLVE_PIP_IP_UPDATE_COMMANDS" | sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" >>"$log_file" 2>&1
fi

# 20-05-2025: Enable/Disable blobFuseEnabled in CLOUD_PROPERTIES
if [ "$IS_MIGRATION_SETUP" != "true" ]; then
    sleep 2s
    echo "***** Configuring blobFuseEnabled in CLOUD_PROPERTIES **********"

    if [ "$CLOUD_PROVIDER" == "azure" ]; then
        echo 'use parablu
        db.CLOUD_PROPERTIES.update({},{$set:{"blobFuseEnabled": true}});' >cloud.js
    else
        echo 'use parablu
        db.CLOUD_PROPERTIES.update({},{$set:{"blobFuseEnabled": false}});' >cloud.js
    fi

    sleep 3s
    sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"
else
    echo "Skipping blobFuseEnabled setup for migration"
fi


# 06-08-2025: [BK-27] Set supportParacloudUrl
sleep 2s
echo "***** Modifying supportParacloudUrl in CLOUD_PROPERTIES **********"
echo 'use parablu
db.CLOUD_PROPERTIES.updateOne({},{$set:{"supportParacloudUrl": "https://SUPPORTPARACLOUDPLACEHOLDER/"}});' >cloud.js
sed -i "s|SUPPORTPARACLOUDPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# 31-05-2025: [PC-224] Set Solr URL
sleep 2s
echo "***** Modifying Solr URL CLOUD_PROPERTIES **********"
echo 'use parablu
db.CLOUD_PROPERTIES.updateOne({},{$set:{"solrUrl": "https://CLOUDNAMEPLACEHOLDER/ParacloudSearch/search/"}});' >cloud.js
sed -i "s|CLOUDNAMEPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# 27-05-2025: [PC-214] Add Azure Storage Account details in CLOUD_CREDENTIALS if details are present ONLY
if [ -n "$AZURE_BLOB_IDENTITY" ] && [ -n "$AZURE_BLOB_KEY" ]; then
    echo "**** Setting up Azure Storage Account credentials ****"

    # Single MongoDB session with all operations
    MONGO_COMMANDS=$(
        cat <<EOF
use parablu
db.CLOUD_CREDENTIALS.drop();

db.CLOUD_CREDENTIALS.insertOne({
 "_id": ObjectId('68355fb4968db006a6b0c933'),
 "cloudName": "azureBlob",
 "provider": "azureblob",
 "identity": "$AZURE_BLOB_IDENTITY",
 "credential": "$AZURE_BLOB_KEY",
 "endPointUrl": "",
 "containerName": "",
 "blobTagName": "APN\\\\/1.0 ParaBluInc/1.0 BluVault/2.5.5.3_7",
 "_class": "com.parablu.pcbd.domain.CloudCredentials"
});

db.CLOUD.updateOne(
  {},
  {
    \$set: {
     cloudCredentials: [
       DBRef('CLOUD_CREDENTIALS', ObjectId("68355fb4968db006a6b0c933"))
     ]
    }
  },
  { upsert: true }
);

db.CLOUD_PROPERTIES.updateOne({},{\$set:{"storageProvider": "ParaBlu"}});
EOF
    )

    # Execute all commands in single MongoDB connection
    echo "$MONGO_COMMANDS" | sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" >>"$log_file"

    echo "**** Azure Storage Account credentials setup completed ****"
else
    echo "Azure Storage Account credentials not provided - skipping setup"
fi

sleep 2s
echo "*** Changing paracloud name ******"

echo 'use parablu001
db.PRIVACY_GATEWAY.updateMany({},{$set:{"componentsProperties.paracloudUrl" : "https://GHOSTURL/GHOSTNAME"}});' >>cloud.js
sed -i "s|GHOSTNAME|$newCloudName|" cloud.js
sed -i "s|GHOSTURL|$newNGINXFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "*** Changing gateway name ******"
echo 'use parablu001
db.PRIVACY_GATEWAY.updateMany({},{$set:{"gatewayName" : "GATEWAYPLACEHOLDER"}});' >>cloud.js
sed -i "s|GATEWAYPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "*** Changing bluvault name ******"
echo 'use parablu001
db.BLUVAULT.updateMany({},{$set:{"bluVaultName" : "BLUVAULTPLACEHOLDER"}})' >>cloud.js
sed -i "s|BLUVAULTPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "*** Changing bluvaultparacloud name ******"

echo 'use parablu001
db.BLUVAULT.updateMany({},{$set:{"componentsProperties.paracloudUrl" : "https://BLUVPARACLOUDURLPLACEHOLDER"}})' >>cloud.js
sed -i "s|BLUVPARACLOUDURLPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "*** Changing bluvault_properties paracloud name ******"
echo 'use parablu001
db.BLUVAULT_PROPERTIES.updateMany({},{$set:{"componentsProperties.paracloudUrl" : "https://BLUVPPARACLOUDURLPLACEHOLDER"}})' >>cloud.js
sed -i "s|BLUVPPARACLOUDURLPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "*** Changing Jobconfig name ******"

echo 'use parablu001
db.JOB_CONFIG.updateMany({},{$set:{"jobServerName" : "JOBPLACEHOLDER"}})' >>cloud.js
sed -i "s|JOBPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

sleep 2s
echo "*** Changing PortalProperties name ******"

echo 'use parablu001
db.PORTAL_PROPERTIES.updateMany({},{$set:{"componentName" : "PORTALPLACEHOLDER"}})' >>cloud.js
sed -i "s|PORTALPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

echo "*** Changing MongoProperties name ******"

echo 'use parablu001
db.MONGO_PROPERTIES.updateMany({},{$set:{"mongoIp" : "MONGOPLACEHOLDER"}})' >>cloud.js
sed -i "s|MONGOPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

echo 'use parablu001
db.MONGO_PROPERTIES.updateMany({},{$set:{"customer_name" : "MONGOCLOUDPLACEHOLDER"}})' >>cloud.js
sed -i "s|MONGOCLOUDPLACEHOLDER|$newCloudName|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# Changes made on 25-04-2025
echo "**** Changing AADCREDENTIALS ****"
echo 'use parablu001
db.AADCREDENTIALS.update({},{$set:{"portalRedirectURI" : "PORTALREDIRECTURIPLACEHOLDER/portal/login"}})' >>cloud.js
sed -i "s|PORTALREDIRECTURIPLACEHOLDER|$FULL_URL|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

if [ "$isLicenseFileUploaded" == false ]; then
    echo "License file not uploaded. Running required jobs..."
    echo 'use parablu001
    db.JOB_CONFIG.updateMany({},{$set:{"job.licenseKeyTamperTimer": false}})' >>cloud.js
    sleep 3s
    sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"
else
    echo "License file uploaded."
fi

echo "*** Changing MS Office Backup Policy ******"

echo 'use parablu001
db.OFFICE_BACKUP_POLICY.updateMany({},{$set:{"msAppBluKrypt": "MSOFFICEBLUKRYPTPLACEHOLDER"}})' >>cloud.js
sed -i "s|MSOFFICEBLUKRYPTPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

echo "*** Changing MS App BluKrypt ******"

echo 'use parablu001
db.MS_APP_BLUKRYPT.updateMany({},{$set:{"host": "MSAPPBLUKRYPTPLACEHOLDER"}})' >>cloud.js
sed -i "s|MSAPPBLUKRYPTPLACEHOLDER|$newParaCloudFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

echo "*** Changing MS App Settings ******"

echo 'use parablu001
db.MS_APP_SETTING.updateMany({},{$set:{"portalURL" : "https://GHOSTURL/GHOSTNAME"}})' >>cloud.js
sed -i "s|GHOSTNAME|$newCloudName|" cloud.js
sed -i "s|GHOSTURL|$newNGINXFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

echo "*** Changing EWS App Settings ******"

echo 'use parablu001
db.EWS_APP_SETTING.updateMany({},{$set:{"portalURL" : "https://GHOSTURL/GHOSTNAME"}})' >>cloud.js
sed -i "s|GHOSTNAME|$newCloudName|" cloud.js
sed -i "s|GHOSTURL|$newNGINXFQDN|" cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# 21-05-2025: [PC-185] Add Billing ID in MS_APP_SETTING
echo "*** Adding Billing ID in MS_APP_SETTING ******"

echo 'use parablu001
db.MS_APP_SETTING.updateMany({},{$set:{"billingTenantId": "a53329c6-582f-48e5-b286-15e6bcc658b0"}});' >>cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# 07-02-2026: [PC-709] Enable Conversational AI
echo "*** Enable Conversational AI in CLOUD_PROPERTIES ******"

echo 'use parablu001
db.CLOUD_PROPERTIES.updateMany({},{$set:{"conversationalAI": true}});' >>cloud.js
sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# 30-01-2026: Add / Update IDENTITY_PROVIDER_SETTINGS (Microsoft) - Temporary Change
echo "*** Adding Identity Provider Settings ******"

echo 'use parablu001
db.IDENTITY_PROVIDER_SETTINGS.updateOne(
  { loginMode: "Microsoft" },
  {
    $set: {
      clientId: "f18ddfac-bc1a-4c03-af82-302e02fdf93e",
      secretKey: "fm88Q~2zO5olX5P91RJgByustJMRXKtsgSQqbben",
      tenentId: "",
      redirectURI: "https://api-app.crashplan.com/aad.php",
      endpointRedirectURI: "http://localhost:8967/app",
      portalRedirectURI: "https://api-app.crashplan.com/sso.php",
      loginMode: "Microsoft",
      tenants: [],
      defaultOdbPolicyName: "ODB_STAGING_ODB_POLICY",
      defaultExchangePolicyName: "EX_STAGING_EX_POLICY",
      defaultSharepointPolicyName: "SP_STAGING_SP_POLICY",
      manyToManyMappingEnabled: false,
      groupMapping: [],
      microsoft365BackupMetaData: {
        tenantId: "",
        graphApplicationIds: ["64d570b0-528a-491e-9ee3-6c86bcc44e96"]
      },
      _class: "com.parablu.pcbd.domain.IdentityProviderSettings"
    }
  },
  { upsert: true }
);' >> cloud.js

sleep 3s
sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" <cloud.js >>"$log_file"

# 30-05-2025: [PC-223] Update admin details and then update the password
echo "**** Updating admin details ****"

ADMIN_UPDATE_DETAILS_COMMANDS=$(
    cat <<EOF
use parablu001

db.USER.updateOne(
  { "userName": "admin" },
  {
    \$set:{
        "userName": "admin",
        "emailId": "support@parablu.com",
        "passwdHash": "cd22c30f1eda0a9fd1ba5f1c26901a8b9c7e3c38717f814ab26ee1895b72442a38a6cfac86474b21bd9d7af6990f28c450cc608bd4d82e4aaf21af201ba25501",
        "lastModifiedTimestamp": "1748674836106",
        "securityRecoveryKey": "3f8bcc0c-2fbf-43c3-8006-027ad653298a",
        "active": true,
        "admin": true,
        "guest": false,
        "firstLogin": false,
        "syncEnabled": false,
        "backupEnabled": true,
        "shareEnabled": true,
        "onedriveBkpEnabled": true,
        "exchangeBkpEnabled": false,
        "sharePointBkpEnabled": false,
        "serverBackupEnabled": false,
        "createdTimestamp": "1461161720580",
        "policyName": "STAGING_POLICY",
        "oneDrivePolicyName": "ODB_STAGING_ODB_POLICY",
        "readOnlyAdmin": false,
        "deleted": false,
        "lastLoggedInTime": "1748674827862",
        "localUser": true,
        "policyModifiedTime": Long("0"),
        "syncPolicyModifiedTime": Long("0"),
        "isSuspended": false,
        "isNewOdbUser": false,
        "failedMailBox": false,
        "backupTargetAssigned": false,
        "backupTargetErrorCode": 0,
        "softBlockEnabled": false,
        "softBlockedTime": Long("0"),
        "noOfDaysForAutoBlock": Long("0"),
        "consentGivenTime": Long("0"),
        "delegatedAdmin": false,
        "spAdmin": false,
        "gmailBkpEnabled": false,
        "site": false,
        "spPolicyName": "SP_STAGING_SP_POLICY",
        "exchangePolicyName": "EX_STAGING_EX_POLICY",
        "superAdmin": false,
        "gdriveBkpEnabled": false,
        "msEXProtectionTime": Long("0"),
        "msODBProtectionTime": Long("0"),
        "msSPProtectionTime": Long("0"),
        "syncDestinationCollection": "BACKUP_2",
        "userNameLowerCase": "admin",
        "accountStatus": false,
        "_class": "com.parablu.pcbd.domain.User"
    }
  },
  { "upsert": true }
)
EOF
)

# Execute the update command
echo "$ADMIN_UPDATE_DETAILS_COMMANDS" | sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" >>"$log_file"

echo "**** Updated admin details successfully ****"

# 29-05-2025: Keeper changes
echo "**** Updating admin password and firstLogin ****"

ADMIN_UPDATE_COMMANDS=$(
    cat <<EOF
use parablu001

db.USER.updateOne(
  { "userName": "admin" },
  {
    \$set: {
      "passwdHash": "$ADMIN_PORTAL_PASSWORD_HASH",
      "firstLogin": false
    }
  }
)
EOF
)

# Execute the update command
echo "$ADMIN_UPDATE_COMMANDS" | sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" >>"$log_file"

echo "**** admin password and firstLogin update completed ****"

echo "Changing passwords for ubuntu and parablu users..."

# Set it for both users
for user in ubuntu parablu; do
    if id "$user" &>/dev/null; then
        echo "$user:$VM_PASSWORD" | sudo chpasswd
        echo "Password set for user: $user"
	echo "PASSWPRD: $VM_PASSWORD"
    else
        echo "User $user does not exist"
    fi
done

echo "Passwords for ubuntu and parablu users changed successfully..."

# Install MongoDB Exporter
echo "*** Installing MongoDB Exporter ******"

# Generate random password for monitoring admin
MONITORING_PASSWORD=$(openssl rand -base64 16 | tr -d "=+/" | cut -c1-16)

# Download and install MongoDB exporter
wget https://github.com/percona/mongodb_exporter/releases/download/v0.34.0/mongodb_exporter-0.34.0.linux-amd64.tar.gz

tar xvzf mongodb_exporter-0.34.0.linux-amd64.tar.gz

cd mongodb_exporter-0.34.0.linux-amd64

sudo mv mongodb_exporter /usr/local/bin/

# Create systemd service file
sudo tee /etc/systemd/system/mongodb_exporter.service > /dev/null <<EOF
[Unit]
Description=MongoDB Exporter
After=network.target

[Service]
Type=simple
User=root
Group=root
ExecStart=/usr/local/bin/mongodb_exporter --web.listen-address=:48766 --mongodb.uri=mongodb://monitoring_admin:$MONITORING_PASSWORD@localhost:$PORT/admin --collect-all --compatible-mode
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Create monitoring user in MongoDB
echo "*** Creating MongoDB monitoring user ******"
echo "use admin
db.createUser({
  user: \"monitoring_admin\",
  pwd: \"$MONITORING_PASSWORD\",
  roles: [
    { role: \"clusterMonitor\", db: \"admin\" },
    { role: \"readAnyDatabase\", db: \"admin\" }
  ]
})
db.getUsers()" > monitoring_user.js

sudo mongo localhost:$PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < monitoring_user.js >> "$log_file"

# Clean up temporary files
rm -f monitoring_user.js
cd ..
rm -rf mongodb_exporter-0.34.0.linux-amd64*

# Allow 48766 port
ufw allow 48766

# Enable and start the service
sudo systemctl daemon-reload
sudo systemctl enable mongodb_exporter
sudo systemctl start mongodb_exporter

# Check service status
echo "*** MongoDB Exporter Service Status ******"
sudo systemctl status mongodb_exporter >> "$log_file"

echo "*** MongoDB Exporter installation completed ******"

# Install Node Exporter
echo "*** Installing Node Exporter ******"

# Download the latest Node Exporter v1.9.1
wget https://github.com/prometheus/node_exporter/releases/download/v1.9.1/node_exporter-1.9.1.linux-amd64.tar.gz

# Extract the archive
tar xvzf node_exporter-1.9.1.linux-amd64.tar.gz

# Navigate to the extracted directory
cd node_exporter-1.9.1.linux-amd64

# Move the binary to /usr/local/bin/
mv node_exporter /usr/local/bin/

# Create systemd service file
sudo tee /etc/systemd/system/node_exporter.service > /dev/null <<EOF
[Unit]
Description=Node Exporter
After=network.target

[Service]
Type=simple
User=root
Group=root
ExecStart=/usr/local/bin/node_exporter --web.listen-address=:48767
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Allow 48767 port
ufw allow 48767

# Reload systemd daemon
sudo systemctl daemon-reload
sudo systemctl enable node_exporter
sudo systemctl start node_exporter

# Check service status
echo "*** Node Exporter Service Status ******"
sudo systemctl status node_exporter >> "$log_file"

echo "*** Node Exporter installation completed ******"

# Allow 48765 port
ufw allow 48765

echo "Adding Apache4 status" >>"$log_file"
mkdir /var/run/apache4
chown -R www-data /var/run/apache4
sleep 2s

echo "Stopping all services" >>"$log_file"
#Stopping All the services:
service apache2 stop && service apache4 stop && service tomcat-pcb1 stop && service tomcat-job1 stop && service cron stop && service mongod stop

# 04-03-2025: List of services to check if they are in "stopped" state. Else exit the script.
SERVICES=("apache2" "apache4" "tomcat-pcb1" "tomcat-job1" "cron" "mongod")

MAX_RETRIES=5 # Number of retries
WAIT_TIME=5   # Wait time between retries (in seconds)

# Function to check if a service is stopped
is_service_stopped() {
    local service_name="$1"
    ! systemctl is-active --quiet "$service_name" # Returns true if inactive
}

# Check if the services have stopped
for SERVICE in "${SERVICES[@]}"; do
    attempt=1
    while ! is_service_stopped "$SERVICE"; do
        if [[ $attempt -ge $MAX_RETRIES ]]; then
            echo "$SERVICE failed to stop after $MAX_RETRIES attempts."
        fi
        echo "$SERVICE is still running. Retrying in $WAIT_TIME seconds... (Attempt $attempt/$MAX_RETRIES)"
        sleep $WAIT_TIME
        ((attempt++))
    done
    echo "$SERVICE is stopped."
done

echo "All services have been successfully stopped!"

#Move the current
mv /parablu/$oldCloudName /parablu/$newCloudName

format_and_mount_disk() {
    local disk=$1

    echo "Formatting and mounting $disk..." >>"$log_file"
    if [ -z "$disk" ]; then
        echo "The disk value is empty. Exiting the script." >>"$log_file"
        exit 1
    fi

    if [ "$CLOUD_PROVIDER" == "linode" ]; then
        # Linode volume handling - simple format and mount
        echo "Linode volume detected: $disk" >>"$log_file"

        # Format the volume with ext4
        sudo mkfs.ext4 "$disk"

        # Create mount point
        sudo mkdir -p /parablu

        # Mount the volume
        sudo mount "$disk" /parablu

        echo "Linode volume $disk formatted and mounted successfully at /parablu." >>"$log_file"
    else
        # Azure (or other) disk handling
        echo "Azure volume detected: $disk" >>"$log_file"

        # Create a GPT partition table and an XFS partition
        sudo parted /dev/$disk --script mklabel gpt mkpart xfspart xfs 0% 100%

        # Create an ext4 filesystem on the disk
        sudo mkfs.ext4 -F /dev/${disk}

        # Inform the OS of partition changes
        sudo partprobe /dev/$disk

        # Create a mount point
        sudo mkdir -p /parablu

        # Mount the new filesystem
        sudo mount /dev/${disk} /parablu

        echo "/dev/$disk formatted and mounted successfully at /parablu." >>"$log_file"
    fi
}

add_fstab() {
    local disk=$1
    sleep 2
    
    if [ "$CLOUD_PROVIDER" == "linode" ]; then
        # Linode: disk is already the full path (e.g. /dev/disk/by-id/scsi-0Linode_Volume_xxx)
        uuid=$(blkid -s UUID -o value "$disk")
        echo "Fetching UUID for Linode volume $disk..." >>"$log_file"
    else
        # Azure/other: disk is just the device name (e.g. sdc)
        uuid=$(blkid -s UUID -o value '/dev/'$disk)
        echo "Fetching UUID for /dev/$disk..." >>"$log_file"
    fi

    if [ -z "$uuid" ]; then
        echo "The UUID value is empty. Exiting the script." >>"$log_file"
        exit 1
    else
        echo "Adding $disk to /etc/fstab"
        echo "UUID=$uuid /parablu ext4 defaults,noatime,nofail 0 2" | sudo tee -a /etc/fstab
        echo "$disk added to /etc/fstab successfully." >>"$log_file"
    fi
}

swapfileadd() {
    # Get the total RAM size in MB
    ram_size=$(free -g | awk '/^Mem:/{print $2}')
    swap_round=$((ram_size + 1))
    swap_size=$((swap_round * 2))
    swap_file="/parablu/swapfile"

    sudo fallocate -l $swap_size'G' $swap_file
    chmod 600 $swap_file
    mkswap $swap_file
    swapon $swap_file
    cp /etc/fstab /etc/fstab.backup.1
    echo "$swap_file swap swap defaults 0 0" | sudo tee -a /etc/fstab

}

echo "Moving /parablu to /parabluold" >>"$log_file"
mv /parablu /parabluold
sleep 2
# Print the output of lsblk
echo "Listing block devices:" >>"$log_file"
lsblk

#echo "Enter the empty and new disk (e.g., sda or sdc or sdb or sdd) - which is not mounted anywhere and used for /parablu"
#read diskvar
# Disk detection logic
diskvar=""
if [ "$CLOUD_PROVIDER" == "linode" ]; then
    # For Linode, look for volume by filesystem path
    echo "Detecting Linode volume..." >>"$log_file"
    
    # Linode volumes are typically at /dev/disk/by-id/scsi-0Linode_Volume_*
    for volume_path in /dev/disk/by-id/scsi-0Linode_Volume_*; do
        if [ -e "$volume_path" ]; then
            # Check if it's the right size
            size_in_bytes=$(sudo blockdev --getsize64 "$volume_path")
            size_in_gb=$((size_in_bytes / 1024 / 1024 / 1024))
            
            if [ $size_in_gb -ge $((${dataDiskSizeGB} - 2)) ] && [ $size_in_gb -le $((${dataDiskSizeGB} + 2)) ]; then
                diskvar="$volume_path"  # Full path for Linode
                echo "Found suitable Linode volume: $diskvar (${size_in_gb}GB)" >>"$log_file"
                break
            fi
        fi
    done
else
    # Azure or other providers: detect unrecognised empty disk
    for disk in $(ls /dev/sd* | grep -v -E '1|2|3|4|5|6|7|8|9' | sed 's/\/dev\///'); do
        if sudo parted -s /dev/$disk print 2>&1 | grep -q 'unrecognised disk label'; then
            size_in_bytes=$(sudo blockdev --getsize64 "/dev/$disk")
            size_in_gb=$((size_in_bytes / 1024 / 1024 / 1024))

            if [ $size_in_gb -ge $((${dataDiskSizeGB} - 2)) ] && [ $size_in_gb -le $((${dataDiskSizeGB} + 2)) ]; then
                diskvar=$disk
                echo "Found suitable Azure/Other disk: /dev/$disk (${size_in_gb}GB)" >>"$log_file"
                break
            fi
        fi
    done
fi

if [ -z "$diskvar" ]; then
    echo "No suitable disk found" >>"$log_file"
    exit 1
fi

if [ -z "$diskvar" ]; then
    echo "No suitable disk found" >>"$log_file"
    exit 1
fi

format_and_mount_disk $diskvar
add_fstab $diskvar
sleep 2
cp -rp /parabluold/* /parablu/
sleep 2
swapfileadd

# 04-03-2025: Check if IPv6 is enabled and store result as "Yes" or "No". If not enabled, remove "address="::1"" from server.xml
IPV6_ENABLED=$(ip -6 addr show scope global | grep -q "inet6" && echo "Yes" || echo "No")

echo "IPv6 enabled: $IPV6_ENABLED"

# If IPv6 is disabled, modify server.xml
# If IPv6 is disabled or provider is Linode, modify server.xml
if [ "$IPV6_ENABLED" = "No" ] || [ "$CLOUD_PROVIDER" = "linode" ]; then
    echo "IPv6 is not enabled. Checking server.xml for address=\"::1\"..."

    # Define file paths
    CONFIG_FILE="/var/lib/tomcat-pcb1/conf/server.xml"
    BACKUP_FILE="/var/lib/tomcat-pcb1/conf/server.xml.bkp"

    # Check if address="::1" is present
    if grep -q 'address="::1"' "$CONFIG_FILE"; then
        echo "Found address=\"::1\". Modifying server.xml..."

        # Create a backup of the original file
        cp "$CONFIG_FILE" "$BACKUP_FILE"

        # Remove address="::1" from the specific line
        sed -i 's/ address="::1"//g' "$CONFIG_FILE"

        echo "Modification complete. Backup saved as $BACKUP_FILE"
    else
        echo "address=\"::1\" not present in server.xml. Moving on..."
    fi
fi

# Change the CATALINA_OPTS value depending on the RAM size
# Get total RAM in KB
total_ram_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}')

# Convert KB to MB
total_ram_mb=$((total_ram_kb / 1024))

# Calculate half of total RAM in MB
half_ram_mb=$((total_ram_mb / 2))
half_ram_value=$(((half_ram_mb / 2) + 100))

# Files to update
files=(
    "/etc/init.d/tomcat-pcb1"
    "/etc/init.d/tomcat-job1"
)

# Update the CATALINA_OPTS in each file
for file in "${files[@]}"; do
    if [[ -f "$file" ]]; then
        sed -i "s/-Xmx[0-9]\+m/-Xmx${half_ram_value}m/" "$file"
        echo "Updated $file with -Xmx${half_ram_value}m"
    else
        echo "File $file not found!"
    fi
done

# Reload systemd daemon (if applicable)
if command -v systemctl &>/dev/null; then
    systemctl daemon-reload
    echo "Reloaded systemd daemon."
fi

echo "Starting all services" >>"$log_file"
service mongod start
sleep 2
service tomcat-pcb1 start && service tomcat-job1 start && service cron start && service apache2 start && service apache4 start

# 04-03-2025: Define services to check if they are in "started" state. Else exit the script.
SERVICES=("apache2" "apache4" "tomcat-pcb1" "tomcat-job1" "cron" "mongod")
MAX_RETRIES=5
WAIT_TIME=5 # Wait time between retries (in seconds)

# Function to check if a service is running
check_service() {
    local service_name="$1"
    systemctl is-active --quiet "$service_name"
}

# Iterate through each service
for SERVICE in "${SERVICES[@]}"; do
    echo "Checking if $SERVICE is running..."

    # Retry logic if the service is not running
    attempt=1
    while ! check_service "$SERVICE"; do
        if [[ $attempt -ge $MAX_RETRIES ]]; then
            echo "$SERVICE failed to start after $MAX_RETRIES attempts."
        fi
        echo "$SERVICE is not running. Retrying in $WAIT_TIME seconds... (Attempt $attempt/$MAX_RETRIES)"
        sleep $WAIT_TIME
        ((attempt++))
    done

    echo "$SERVICE is running."
done

echo "All services are up and running!"

# Update the SSL certificate based on this patch - the install.sh in ISO was using old cert file
# Update the SSL certificate based on this patch - the install.sh in ISO was using old cert file
if [ "$IS_MIGRATION_SETUP" != "true" ]; then
    if [ "$tenant" = "crashplan" ]; then
        wget --user="$DNS_USERNAME" --password="$DNS_PASSWORD" https://dns.parablu.com/parablu_installables/scripts/newdeploy/updateCPCert.sh
        sleep 2
        sudo bash updateCPCert.sh
    else
        wget --user="$DNS_USERNAME" --password="$DNS_PASSWORD" https://dns.parablu.com/parablu_installables/scripts/newdeploy/updateCert.sh
        sleep 2
        sudo bash updateCert.sh
    fi
else
    echo "Skipping SSL certificate update for migration setup"
fi

# Set timezone of VM based on region/location
echo "[INFO] Fetching region from instance metadata..."

if [ "$CLOUD_PROVIDER" == "linode" ]; then
    # For Linode, get region from Linode metadata API with proper authentication
    TOKEN=$(curl -s -X PUT -H "Metadata-Token-Expiry-Seconds: 3600" http://169.254.169.254/v1/token)
    
    if [ -n "$TOKEN" ]; then
        # Get full instance data and extract region
        region=$(curl -s -H "Metadata-Token: $TOKEN" http://169.254.169.254/v1/instance | grep "region:" | cut -d' ' -f2 | tr '[:upper:]' '[:lower:]')
    fi
    
    # If Linode metadata fails, fall back to a default or use the region passed to the script
    if [ -z "$region" ]; then
        # Use the region parameter passed to the script (like 'ap-west')
        region=$(echo "$6" | sed 's|https://[^/]*/||' | cut -d'/' -f1)  # Extract from API URL if available
        if [ -z "$region" ]; then
            region="ap-west"  # Default fallback
        fi
    fi
else
    # Azure logic (original)
    region=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/instance/compute/location?api-version=2021-02-01&format=text" | tr '[:upper:]' '[:lower:]')
fi

echo "[INFO] Detected region: $region"

case "$region" in
  centralindia|ap-west)
    timezone="Asia/Kolkata"
    ;;
  eastus|us-east)
    timezone="America/New_York"
    ;;
  westus|westus3|us-west)
    timezone="America/Los_Angeles"
    ;;
  uaenorth)
    timezone="Asia/Dubai"
    ;;
  eu-west)
    timezone="Europe/London"
    ;;
  ap-southeast)
    timezone="Asia/Singapore"
    ;;
  *)
    echo "[ERROR] Unknown or unsupported region: $region, defaulting to UTC"
    timezone="UTC"
    ;;
esac

echo "[INFO] Mapping region '$region' to timezone '$timezone'"
echo "[INFO] Setting system timezone to '$timezone'..."
sudo timedatectl set-timezone "$timezone"

echo "[SUCCESS] Timezone set to: $(timedatectl | grep 'Time zone')"

sleep 2
echo "Server is ready - Finish the FQDN and Hardening use the below URL with help of DevOps and share the URL with Customer for next acctions. Thanks!"
echo "https://$newNGINXFQDN/$newCloudName"

#        break  # Exit the loop if confirmed
#Configuration else
#    else
#        echo "Configuration not confirmed. Please retry."
#   fi
#done

