#!/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

RETURN_CODE=0

if [ ! -f /opt/so/state/eaintegrations.txt ]; then
  # First, check for any package upgrades
  /usr/sbin/so-elastic-fleet-package-upgrade

  # Second, update Fleet Server policies
  /usr/sbin/so-elastic-fleet-integration-policy-elastic-fleet-server

  # Third, configure Elastic Defend Integration seperately
  /usr/sbin/so-elastic-fleet-integration-policy-elastic-defend

  # Each group fetches its agent policy once and dispatches create/update writes concurrently.

  # Initial Endpoints
  elastic_fleet_load_integrations_dir "endpoints-initial" \
    /opt/so/conf/elastic-fleet/integrations/endpoints-initial "Initial Endpoints Policy" || RETURN_CODE=1

  # Grid Nodes - General
  elastic_fleet_load_integrations_dir "so-grid-nodes_general" \
    /opt/so/conf/elastic-fleet/integrations/grid-nodes_general "Grid Nodes Policy_General" || RETURN_CODE=1

  # Grid Nodes - Heavy
  elastic_fleet_load_integrations_dir "so-grid-nodes_heavy" \
    /opt/so/conf/elastic-fleet/integrations/grid-nodes_heavy "Grid Nodes Policy_Heavy" || RETURN_CODE=1

  # Fleet Server - Optional integrations (one agent policy per FleetServer_* directory)
  for FLEET_DIR in /opt/so/conf/elastic-fleet/integrations-optional/FleetServer*/; do
    [ -d "$FLEET_DIR" ] || continue
    FLEET_POLICY=$(basename "$FLEET_DIR")
    elastic_fleet_load_integrations_dir "$FLEET_POLICY" \
      "${FLEET_DIR%/}" "Fleet Server Policy" "elasticsearch-logs" || RETURN_CODE=1
  done

  # Only create the state file if all policies were created/updated successfully
  if [[ "$RETURN_CODE" != "1" ]]; then
    touch /opt/so/state/eaintegrations.txt
  fi
else
  exit $RETURN_CODE
fi
