#!/bin/sh

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

# Send the inventory

SYSTEM_ID=$(uci -q get ns-plug.config.system_id)
SYSTEM_SECRET=$(uci -q get ns-plug.config.secret)
URL=$(uci -q get ns-plug.config.inventory_url)
TYPE=$(uci -q get ns-plug.config.type)

if [ -z "$SYSTEM_ID" ] || [ -z "$SYSTEM_SECRET" ]; then
    # System ID and System secret not found, configure ns-plug to enable it
    exit 0
fi

echo "{\"data\": {\"lk\": \"$SYSTEM_ID\", \"data\": $(/usr/sbin/inventory) }}" | \
/usr/bin/curl -m 180 --retry 5 -L -s \
   --header "Authorization: token $SYSTEM_SECRET"  --header "Content-Type: application/json" --header "Accept: application/json"  \
   --data-binary @- "$URL" > /dev/null

if [ $? -ne 0 ]; then
    status="error"
else
    status="success"
fi

echo '{"status": "'$status'", "last_attempt": "'$(date -Iseconds)'"}' > /tmp/inventory-sent.json

if [ "$TYPE" = "enterprise" ]; then
    # Update registration date
    /usr/bin/curl -m 180 --retry 5 -L -s \
        --header "Content-Type: application/json" --header "Accept: application/json"  \
        -d '{"secret":"'$SYSTEM_SECRET'"}' https://my.nethesis.it/api/systems/info >/dev/null

    # Temporary send data to new endpoint
    # To be removed when the migration to new my.nethesis.it will be completed
    /usr/sbin/phonehome | /usr/bin/curl -m 180 --retry 3 -L -s --user "$SYSTEM_ID:$SYSTEM_SECRET" \
        -H "Content-Type: application/json" \
        --data-binary @- https://my.nethesis.it/proxy/inventory >/dev/null || :
fi
