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

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

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

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

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

source $PARABLU_COMPONENT_SCRIPT_PATH
source $PARABLU_CONFIG_SCRIPT_PATH

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

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

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

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

        fi
fi

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

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

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

#        echo "Configuring Tomcat services..."
#        log_exec cp -r /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-cloudproperty.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
#        log_exec cp -r /var/lib/tomcat-pcb1/webapps/paracloud/WEB-INF/classes/pb-credential.properties /var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/
#        echo "Stopping Tomcat services..."
#        log_exec service tomcat-pcb1 stop
#        log_exec service tomcat-job1 stop
#        sleep 2s
#        cd /var/lib/tomcat-pcb1/webapps/
#        log_exec rm -rf paralite.war
#        sleep 1s
#        cd -
#        sleep 2s
#        echo "Starting Tomcat services..."
#        log_exec service tomcat-pcb1 restart
#        log_exec service tomcat-job1 restart
#fi

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

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

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

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

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

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

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

fi

if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "3 1" ] || [ "$SERVER_TYPE" == "2" ]; then
    # ==========================================
    # 11-09-2025: PC-409 MongoDB Configuration Patch
    # ==========================================
    CERT_URL="https://letsencrypt.org/certs/isrgrootx1.pem"
    CERT_FILE="isrgrootx1.pem"
    ALIAS="mongodbAtlasRootCA"
    KEYSTORE="/etc/ssl/certs/java/cacerts"

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

    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/dev/$CLOUD_NAME/g" "${PB_CREDS_FILE%/*}/pb-cloudproperty.properties"
        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

    # 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..."
                COMMENT="# MongoDB Configuration - Non-Clustered Setup"
                DB_PARABLU_VALUE='mongodb://$PB{db_user}:$PB{db_password}@$PB{db_host1}:$PB{db_port1},$PB{db_host2}:$PB{db_port2},$PB{db_host3}:$PB{db_port3}/'

                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."
                break
                ;;

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

                # Loop until valid mongoFQDN is provided
                while true; do
                    read -p "Mongo FQDN (e.g., cluster0.abc123.mongodb.net): " mongoFQDN
                    if [[ -n "$mongoFQDN" ]]; then
                        break
                    else
                        echo "Error: Mongo FQDN cannot be empty. Please try again."
                    fi
                done

                # Loop until valid appName is provided
                while true; do
                    read -p "App Name: " appName
                    if [[ -n "$appName" ]]; then
                        break
                    else
                        echo "Error: App Name cannot be empty. Please try again."
                    fi
                done

                COMMENT="# MongoDB Configuration - Clustered Setup"
                DB_PARABLU_VALUE="mongodb+srv://\$PB{db_user}:\$PB{db_password}@${mongoFQDN}/?retryWrites=true&w=majority&appName=${appName}"

                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 "Mongo FQDN: $mongoFQDN"
                echo "App Name: $appName"

                # Certificate import only needed for clustered setup
                echo "=== Checking if certificate already exists ==="
                if sudo keytool -list -keystore "$KEYSTORE" -alias "$ALIAS" -storepass changeit >/dev/null 2>&1; then
                    echo "Certificate with alias '$ALIAS' already exists in keystore. Skipping certificate import."
                else
                    echo "=== Downloading certificate ==="
                    curl -s -O "$CERT_URL"

                    read -sp "Enter Java keystore password: " STOREPASS
                    echo ""

                    echo "=== Importing certificate into Java keystore ==="
                    sudo keytool -importcert \
                      -trustcacerts \
                      -noprompt \
                      -alias "$ALIAS" \
                      -file "$CERT_FILE" \
                      -keystore "$KEYSTORE" \
                      -storepass "$STOREPASS"

                    echo "Certificate imported successfully!"
                fi
                break
                ;;

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

    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

    echo "Configuration completed successfully for all files!"

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

    # ==========================================
    # Update GLOBAL_EXCLUDED_FOLDERS for Gmail Trash
    # ==========================================
    echo "=== Updating GLOBAL_EXCLUDED_FOLDERS for Gmail Trash folder ==="

    mongo --quiet --norc localhost:"$MONGODB_PORT" -u "neil" -p "parablu" --authenticationDatabase "admin" > /dev/null 2>&1 << 'EOF'
use parablu001
db.GLOBAL_EXCLUDED_FOLDERS.updateOne(
  { osType: 'gmail', folderPath: 'Trash' },
  {
    $setOnInsert: {
      _class: 'com.parablu.pcbd.domain.GLOBAL_EXCLUDED_FOLDERS'
    }
  },
  { upsert: true }
);
EOF

    echo "GLOBAL_EXCLUDED_FOLDERS update completed."

    # ==========================================
    # Update domain from CLOUD_PROPERTIES
    # ==========================================
    echo "=== Updating domain configuration from CLOUD_PROPERTIES ==="

    echo "Extracting domain from MongoDB CLOUD_PROPERTIES collection..."

    # Extract supportParacloudUrl and strip https:// and trailing /
    DOMAIN=$(mongo --quiet localhost:"$MONGODB_PORT" -u "neil" -p "parablu" --authenticationDatabase "admin" --eval "db.getSiblingDB('parablu').CLOUD_PROPERTIES.findOne({}, {supportParacloudUrl: 1}).supportParacloudUrl" | grep -v "^switched to db" | grep -v "^bye$" | sed 's|^https\?://||' | sed 's|/$||')

    # Alternative method if the above doesn't work - using printjson
    if [ -z "$DOMAIN" ] || [[ "$DOMAIN" == *"switched"* ]]; then
        DOMAIN=$(mongo --quiet localhost:"$MONGODB_PORT" -u "neil" -p "parablu" --authenticationDatabase "admin" << 'EOF' | grep -v "switched to db" | grep -v "^bye$" | tail -1
use parablu
var doc = db.CLOUD_PROPERTIES.findOne({}, {supportParacloudUrl: 1});
if (doc && doc.supportParacloudUrl) {
    var url = doc.supportParacloudUrl;
    url = url.replace(/^https?:\/\//, '');
    url = url.replace(/\/$/, '');
    print(url);
}
EOF
)
    fi

    # Trim any whitespace from the domain
    DOMAIN=$(echo "$DOMAIN" | tr -d '\n' | tr -d '\r' | xargs)

    if [ -z "$DOMAIN" ] || [[ "$DOMAIN" == *"ERROR"* ]] || [[ "$DOMAIN" == *"switched"* ]]; then
        echo "Error: Could not extract domain from MongoDB. Skipping domain update."
    else
        echo "Extracted domain: $DOMAIN"
        echo "Domain extracted: $DOMAIN" >> "$LOG_FILE"

        # Update pb-credential.properties file
        CRED_FILE="/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/pb-credential.properties"
        if [ -f "$CRED_FILE" ]; then
            echo "Processing: $CRED_FILE"

            # Update db_host entries (without numbers)
            sed -i "s/^db_host=.*/db_host=$DOMAIN/" "$CRED_FILE"

            # Update all db_host{N} entries (with numbers)
            sed -i "s/^db_host\([0-9]\+\)=.*/db_host\1=$DOMAIN/" "$CRED_FILE"

            echo "Updated db_host entries in $CRED_FILE" >> "$LOG_FILE"

        else
            echo "Warning: File $CRED_FILE not found - skipping."
        fi

        # Update pb-cloudproperty.properties file
        CLOUD_FILE="/var/lib/tomcat-pcb1/webapps/paralite/WEB-INF/classes/pb-cloudproperty.properties"
        if [ -f "$CLOUD_FILE" ]; then
            echo "Processing: $CLOUD_FILE"

            # Update componentName
            sed -i "s/^componentName=.*/componentName=$DOMAIN/" "$CLOUD_FILE"

            echo "Updated componentName in $CLOUD_FILE" >> "$LOG_FILE"

            # Show what was updated
            echo "Updated componentName to: $DOMAIN"
        else
            echo "Warning: File $CLOUD_FILE not found - skipping."
        fi

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

else
    echo "SERVER_TYPE=$SERVER_TYPE does not match criteria. Skipping patch."
fi
