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

    for PB_CREDS_FILE in "${PB_CREDS_FILES[@]}"; do
        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

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

        2)
            echo "Configuring for Clustered Setup..."
            read -p "Mongo FQDN (e.g., cluster0.abc123.mongodb.net): " mongoFQDN
            read -p "App Name: " appName

            if [[ -z "$mongoFQDN" || -z "$appName" ]]; then
                echo "Error: Both Mongo FQDN and App Name are required for clustered setup."
                exit 1
            fi

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

        *)
            echo "Invalid selection. Please run the script again and choose 1 or 2."
            exit 1
            ;;
    esac

    # Check if certificate already exists in keystore
    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

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

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

