#!/bin/bash

#
# Copyright (C) 2024 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

#
# Push report data a remote NethSecurity controller
#

UCI_CONF="ns-plug"
source /etc/os-release

server=$(uci -q get ${UCI_CONF}.config.server)
unit_id=$(uci -q get ${UCI_CONF}.config.unit_id)
token=$(uci -q get ${UCI_CONF}.config.token)
unit_name=$(uci -q get ${UCI_CONF}.config.unit_name)
vpn_address=$(uci -q get ${UCI_CONF}.config.vpn_address)
api_port=$(uci -q get ${UCI_CONF}.config.api_port)
if [ -n "${vpn_address}" ] && [ -n "${api_port}" ]; then
    url="http://${vpn_address}:${api_port}/ingest"
else
    url="${server}/api/ingest"
fi

# Exit early if no server has been set
if [ -z "${server}" ]; then
    exit 1
fi

# Exit early if no unit_id has been set
if [ -z "${unit_id}" ]; then
    exit 2
fi

# Exit early if no token been set
if [ -z "${token}" ]; then
    exit 3
fi

# Disable certificate verification if tls_verify is set to 0
curl_opts="--fail -sL"
tls_verify=$(uci -q get ${UCI_CONF}.config.tls_verify)
if [ "${tls_verify}" == "0" ]; then
    curl_opts="${curl_opts}k"
fi

# Create an array with all dump APIs, dump-nsplug-config is a special case and must be called before the others
dump_apis=(
    "dump-nsplug-config"
    "dump-ovpn-config"
    "dump-wan-config"
    "dump-ts-malware"
    "dump-ts-attacks"
    "dump-mwan-events"
    "dump-dpi-stats"
    "dump-ovpn-connections"
)
# Loop through all dump APIs and push data
for api in "${dump_apis[@]}"; do
    /usr/libexec/rpcd/ns.controller call ${api} | curl ${curl_opts} \
        -H "Content-Type: application/json" \
        -u ${unit_id}:${token} \
        -o /dev/null \
        ${url}/${api} --data @-
    if [ $? -gt 0 ]; then
	logger -t ns-push-reports "Failed to push $api"
    fi
done
