#!/bin/sh

user="$(id -u)"
if [ "$user" = '0' ]; then
    # if running as root switch to the corelight-fleetd user before proceeding
    script=$(readlink -f "$0")
    exec sudo -u corelight-fleetd "$script" "$@"
fi

# find the conf file from options, with default
_get_conf_file_name() {
    while [ "$#" -gt 0 ]; do
        local opt="$1"; shift
        case "$opt" in
        -c)
            echo "$1"
            return
            ;;
        -c=*)
            echo "${opt#c=}"
            return
            ;;
        esac
    done
    echo "corelight-fleetd.conf"
}

# Gets the data path from the confFile
_get_data_path() {
    # Would rather use python's full json syntax support to find the value,
    # but RHEL8 does not include a python interpreter by default
    local confFile="$1"
    if [ -r "$confFile" ]; then
        sed -ne '/"data-path"[[:space:]]*:/s/^.*"data-path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*$/\1/p' "$confFile"
    fi
}

confFile="$(_get_conf_file_name "$@")"
dataPath="$(_get_data_path "$confFile")"

# Pull in any environment variables from our environment file.
# The file format is simply
#   VARIABLE=value
# The VARIABLE must start with FLEET_ or CORELIGHT_. The value is used verbatim.
if [ -n "$dataPath" ]; then
    envFile="$dataPath/env/corelight-fleetd"
    if [ -r "$envFile" ]; then
        while IFS="=" read -r var value; do
            case "$var" in
            CORELIGHT_*|FLEET_*)
                export "$var"="$value"
            esac
        done < "$envFile"
    fi
fi

# finally switch to the actual daemon
exec /usr/lib/corelight-fleet/corelight-fleetd "$@"
