#!/bin/sh
# Copyright 2021 Northern.tech AS
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

set -e

# Send all output to stderr, to avoid confusing the inventory parser in the
# client, which should only receive empty output from this script. The actual
# reporting we will do ourselves.
exec 1>&2

CONFIG=${TEST_CONFIG:-/var/lib/mender-configure/device-config.json}
CONFIG_CHECKSUM=${TEST_CONFIG_CHECKSUM:-/var/lib/mender-configure/device-config-reported.sha256}
CONFIG_ENDPOINT=${TEST_CONFIG_ENDPOINT:-api/devices/v1/deviceconfig/configuration}

# If the configuration file doesn't exist, exit silently
if ! [ -f "$CONFIG" ]; then
    exit 0
fi

# Fetch Authentication token and server from Mender Auth Manager.
DBUS_RAW=$(dbus-send \
    --system \
    --print-reply \
    --dest=io.mender.AuthenticationManager \
    /io/mender/AuthenticationManager \
    io.mender.Authentication1.GetJwtToken)

DBUS_REPLY=$(echo "$DBUS_RAW" | sed -ne '/^ *string ".*" *$/ {s/^ *string "\(.*\)" *$/\1/; p}')

AUTH_TOKEN="$(echo "$DBUS_REPLY" | sed -ne '1p')"
SERVER="$(echo "$DBUS_REPLY" | sed -ne '2p')"

if [ -z "$AUTH_TOKEN" ]; then
    echo "mender-inventory-mender-configure: An authentication token could not be obtained over DBus."
    # Don't produce an error. Most likely mender-auth is not ready or
    # the device hasn't been accepted
    exit 0
fi
if [ -z "$SERVER" ]; then
    echo "mender-inventory-mender-configure: A server address could not be obtained over DBus."
    exit 1
fi

# Include the JWT token in the checksum to report again the
# configuration to the server in case of new authorization after
# device decommissioning or connection to a different Mender server
COMPUTED_CHECKSUM="$( (echo "$AUTH_TOKEN"; cat "$CONFIG") | sha256sum -)"

# If checksum hasn't changed since previous report, exit silently.
if [ -f "$CONFIG_CHECKSUM" ] && [ "$COMPUTED_CHECKSUM" = "$(cat "$CONFIG_CHECKSUM")" ]; then
    exit 0
fi

# Do the report.
curl \
    -s \
    -S \
    -Lf \
    -X PUT \
    -H "Authorization: Bearer ${AUTH_TOKEN}" \
    -H "Content-Type: application/json" \
    -d "@${CONFIG}" \
    "${SERVER}/${CONFIG_ENDPOINT}"

# Update checksum atomically.
echo "$COMPUTED_CHECKSUM" > "$CONFIG_CHECKSUM.tmp"
sync "$CONFIG_CHECKSUM.tmp"
mv "$CONFIG_CHECKSUM.tmp" "$CONFIG_CHECKSUM"
sync "$(dirname "$CONFIG_CHECKSUM")"
