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

# shellcheck disable=SC1091
. /usr/sbin/so-common

usage() {
    echo "Usage: $0 <component> [args]"
    echo ""
    echo "Supported args:"
    echo "  --force | -f          Force stop all Salt jobs before starting component."
    echo ""
    echo "Examples:"
    echo "  $0 kibana             Start Kibana"
    echo "  $0 kibana --force     Force stop all Salt jobs before starting Kibana"
    exit 1
}

if [[ $# -lt 1 ]]; then
    usage
fi

#shellcheck disable=SC2154
echo "$banner"
printf "Starting %s...\n\nThis could take a while if another Salt job is running. \nRun this command with --force to stop all Salt jobs before proceeding.\n" "$1"
echo "$banner"
if [[ "$2" = "--force" ]] || [[ "$2" == "-f" ]]; then
	printf "\nForce-stopping all Salt jobs before proceeding\n\n"
	salt-call saltutil.kill_all_jobs
fi

case "$1" in
    "all")
        salt-call state.highstate queue=True
        ;;
   	"elastic-fleet"|"elasticfleet")
        if docker_check_running "elastic-fleet"; then
            printf "\nso-%s is already running!\n\n" "elastic-fleet"
            /usr/sbin/so-status
        else
            docker rm "so-elastic-fleet" 2> /dev/null
            salt-call state.apply elasticfleet queue=True
        fi
        ;;
   	*)
        if docker_check_running "$1"; then
            printf "\nso-%s is already running\n\n" "$1"
            /usr/sbin/so-status
        else
            docker rm "so-${1}" 2> /dev/null
            salt-call state.apply "$1" queue=True
        fi
        ;;
esac
