#!/bin/bash
# Copyright Security Onion Solutions LLC and/or licensed to Security Onion Solutions LLC under one
# or more contributor license agreements. Licensed under the Elastic License 2.0 as shown at
# https://securityonion.net/license; you may not use this file except in compliance with the
# Elastic License 2.0.

. /usr/sbin/so-elastic-fleet-common

curl_output=$(curl -s -K /opt/so/conf/elasticsearch/curl.config -c - -X GET http://localhost:5601/)
if [ $? -ne 0 ]; then
    echo "Error: Failed to connect to Kibana."
    exit 1
fi

IFS=$'\n'
agent_policies=$(elastic_fleet_agent_policy_ids)
if [ $? -ne 0 ]; then
    echo "Error: Failed to retrieve agent policies."
    exit 1
fi

for AGENT_POLICY in $agent_policies; do
    integrations=$(elastic_fleet_integration_policy_names "$AGENT_POLICY")
    for INTEGRATION in $integrations; do
        if ! [[ "$INTEGRATION" == "elastic-defend-endpoints" ]] && ! [[ "$INTEGRATION" == "fleet_server-"* ]]; then
            # Get package name so we know what package to look for when checking the current and latest available version
            PACKAGE_NAME=$(elastic_fleet_integration_policy_package_name "$AGENT_POLICY" "$INTEGRATION")

            # Get currently installed version of package
            PACKAGE_VERSION=$(elastic_fleet_integration_policy_package_version "$AGENT_POLICY" "$INTEGRATION")

            # Get latest available version of package
            AVAILABLE_VERSION=$(elastic_fleet_package_latest_version_check "$PACKAGE_NAME")

            # Get integration ID
            INTEGRATION_ID=$(elastic_fleet_integration_id "$AGENT_POLICY" "$INTEGRATION")

            if [[ "$PACKAGE_VERSION" != "$AVAILABLE_VERSION" ]]; then
                # Dry run of the upgrade
                echo "Current $PACKAGE_NAME package version ($PACKAGE_VERSION) is not the same as the latest available package ($AVAILABLE_VERSION)..."
                echo "Upgrading $INTEGRATION..."
                echo "Starting dry run..."
                DRYRUN_OUTPUT=$(elastic_fleet_integration_policy_dryrun_upgrade "$INTEGRATION_ID")
                DRYRUN_ERRORS=$(echo "$DRYRUN_OUTPUT" | jq .[].hasErrors)
                
                # If no errors with dry run, proceed with actual upgrade
                if [[ "$DRYRUN_ERRORS" == "false" ]]; then
                    echo "No errors detected. Proceeding with upgrade..."
                    elastic_fleet_integration_policy_upgrade "$INTEGRATION_ID"
                    if [ $? -ne 0 ]; then
                        echo "Error: Upgrade failed for integration ID '$INTEGRATION_ID'."
                        exit 1
                    fi
                else
                    echo "Errors detected during dry run. Stopping upgrade..."
                    exit 1
                fi
            fi
        fi
    done
done
echo
