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

DEFAULT_SALT_DIR=/opt/so/saltstack/default

if [ -z $NOROOT ]; then
        # Check for prerequisites
        if [ "$(id -u)" -ne 0 ]; then
                echo "This script must be run using sudo!"
                exit 1
        fi
fi

# Ensure /usr/sbin is in path
if ! echo "$PATH" | grep -q "/usr/sbin"; then
  export PATH="$PATH:/usr/sbin"
fi

# Define a banner to separate sections
banner="========================================================================="

elastic_fleet_integration_check() {

    AGENT_POLICY=$1

    JSON_STRING=$2

    NAME=$(jq -r .name $JSON_STRING)

    INTEGRATION_ID=$(/usr/sbin/so-elastic-fleet-agent-policy-view "$AGENT_POLICY" | jq -r '.item.package_policies[] | select(.name=="'"$NAME"'") | .id')

}

elastic_fleet_integration_create() {

    JSON_STRING=$1

    curl -K /opt/so/conf/elasticsearch/curl.config -L -X POST "localhost:5601/api/fleet/package_policies" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$JSON_STRING"
}


elastic_fleet_integration_remove() {

    AGENT_POLICY=$1

    NAME=$2

    INTEGRATION_ID=$(/usr/sbin/so-elastic-fleet-agent-policy-view "$AGENT_POLICY" | jq -r '.item.package_policies[] | select(.name=="'"$NAME"'") | .id')

    JSON_STRING=$( jq -n \
                    --arg INTEGRATIONID "$INTEGRATION_ID" \
                    '{"packagePolicyIds":[$INTEGRATIONID]}'
                    )

    curl -K /opt/so/conf/elasticsearch/curl.config -L -X POST "localhost:5601/api/fleet/package_policies/delete" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$JSON_STRING"
}

elastic_fleet_integration_update() {

    UPDATE_ID=$1

    JSON_STRING=$2

    curl -K /opt/so/conf/elasticsearch/curl.config -L -X PUT "localhost:5601/api/fleet/package_policies/$UPDATE_ID" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$JSON_STRING"
}

elastic_fleet_integration_policy_upgrade() {

    INTEGRATION_ID=$1

    JSON_STRING=$( jq -n \
                    --arg INTEGRATIONID "$INTEGRATION_ID" \
                    '{"packagePolicyIds":[$INTEGRATIONID]}'
                    )

    curl -K /opt/so/conf/elasticsearch/curl.config -L -X POST "localhost:5601/api/fleet/package_policies/upgrade" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$JSON_STRING"
}


elastic_fleet_package_version_check() {
    PACKAGE=$1
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/epm/packages/$PACKAGE" | jq -r '.item.version'
}

elastic_fleet_package_latest_version_check() {
    PACKAGE=$1
    if output=$(curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/epm/packages/$PACKAGE" --fail); then
        if version=$(jq -e -r '.item.latestVersion' <<< $output); then
            echo "$version"
        fi
    else
        echo "Error: Failed to get latest version for $PACKAGE"
    fi
}

elastic_fleet_package_install() {
    PKG=$1
    VERSION=$2
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X POST -H 'kbn-xsrf: true' -H 'Content-Type: application/json'  -d '{"force":true}' "localhost:5601/api/fleet/epm/packages/$PKG/$VERSION"
}

elastic_fleet_bulk_package_install() {
    BULK_PKG_LIST=$1
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X POST -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d@$1 "localhost:5601/api/fleet/epm/packages/_bulk"
}

elastic_fleet_package_is_installed() {
    PACKAGE=$1
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET -H 'kbn-xsrf: true' "localhost:5601/api/fleet/epm/packages/$PACKAGE" | jq -r '.item.status'
}

elastic_fleet_installed_packages() {
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET -H 'kbn-xsrf: true' -H 'Content-Type: application/json' "localhost:5601/api/fleet/epm/packages/installed?perPage=500"
}

elastic_fleet_agent_policy_ids() {
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/agent_policies" | jq -r .items[].id
    if [ $? -ne 0 ]; then
        echo "Error: Failed to retrieve agent policies."
        exit 1
    fi
}

elastic_fleet_agent_policy_names() {
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/agent_policies" | jq -r .items[].name
    if [ $? -ne 0 ]; then
        echo "Error: Failed to retrieve agent policies."
        exit 1
    fi
}

elastic_fleet_integration_policy_names() {
    AGENT_POLICY=$1
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/agent_policies/$AGENT_POLICY" | jq -r .item.package_policies[].name
    if [ $? -ne 0 ]; then
        echo "Error: Failed to retrieve integrations for '$AGENT_POLICY'."
        exit 1
    fi
}

elastic_fleet_integration_policy_package_name() {
    AGENT_POLICY=$1
    INTEGRATION=$2
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/agent_policies/$AGENT_POLICY" | jq -r --arg INTEGRATION "$INTEGRATION" '.item.package_policies[] | select(.name==$INTEGRATION)| .package.name'
    if [ $? -ne 0 ]; then
        echo "Error: Failed to retrieve package name for '$INTEGRATION' in '$AGENT_POLICY'."
        exit 1
    fi
}

elastic_fleet_integration_policy_package_version() {
    AGENT_POLICY=$1
    INTEGRATION=$2

    if output=$(curl -s -K /opt/so/conf/elasticsearch/curl.config -L -X GET "localhost:5601/api/fleet/agent_policies/$AGENT_POLICY" --fail); then
        if version=$(jq -e -r --arg INTEGRATION "$INTEGRATION" '.item.package_policies[] | select(.name==$INTEGRATION)| .package.version' <<< $output); then
            echo "$version"
        fi
    else
        echo "Error: Failed to retrieve agent policy $AGENT_POLICY"
        exit 1
    fi
}

elastic_fleet_integration_id() {
    AGENT_POLICY=$1
    INTEGRATION=$2
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -L -X GET "localhost:5601/api/fleet/agent_policies/$AGENT_POLICY" | jq -r --arg INTEGRATION "$INTEGRATION" '.item.package_policies[] | select(.name==$INTEGRATION)| .id'
    if [ $? -ne 0 ]; then
        echo "Error: Failed to retrieve integration ID for '$INTEGRATION' in '$AGENT_POLICY'."
        exit 1
    fi
}

elastic_fleet_integration_policy_dryrun_upgrade() {
    INTEGRATION_ID=$1
    curl -s -K /opt/so/conf/elasticsearch/curl.config -b "sid=$SESSIONCOOKIE" -H "Content-Type: application/json" -H 'kbn-xsrf: true' -L -X POST "localhost:5601/api/fleet/package_policies/upgrade/dryrun" -d "{\"packagePolicyIds\":[\"$INTEGRATION_ID\"]}"
    if [ $? -ne 0 ]; then
        echo "Error: Failed to complete dry run for '$INTEGRATION_ID'."
        exit 1
    fi
}

elastic_fleet_policy_create() {

    NAME=$1
    DESC=$2
    FLEETSERVER=$3
        TIMEOUT=$4

    JSON_STRING=$( jq -n \
                    --arg NAME "$NAME" \
                    --arg DESC "$DESC" \
                    --arg TIMEOUT $TIMEOUT \
                    --arg FLEETSERVER "$FLEETSERVER" \
                    '{"name": $NAME,"id":$NAME,"description":$DESC,"namespace":"default","monitoring_enabled":["logs"],"inactivity_timeout":$TIMEOUT,"has_fleet_server":$FLEETSERVER}'
                    )
    # Create Fleet Policy
    curl -K /opt/so/conf/elasticsearch/curl.config -L -X POST "localhost:5601/api/fleet/agent_policies" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$JSON_STRING"

}

elastic_fleet_policy_update() {

    POLICYID=$1
    JSON_STRING=$2

    curl -K /opt/so/conf/elasticsearch/curl.config -L -X PUT "localhost:5601/api/fleet/agent_policies/$POLICYID" -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$JSON_STRING"
}

