#!/bin/bash
#
# Copyright (c) 2022-2025 Broadcom. All Rights Reserved.
# Broadcom Confidential. The term "Broadcom" refers to Broadcom Inc.
# and/or its subsidiaries.
#
# Send a business event to the vLCM service. The service is notified by
# sending SIGUSR1 signal. The request is written to event.request file,
# and the service writes the response in event.response file.
#
# Parameters
# $1 is the base64 encoded event request as a parameter, that is then saved to the $eventRequest file.
# If $1 is "file" - event request is already stored in the file, no need to do anything additional
#

eventRequest="/var/run/vmware-vlcm/ndu/upgrade/event.request"
eventResponse="/var/run/vmware-vlcm/ndu/upgrade/event.response"

rm -f $eventResponse
if [ "$1" != "file" ]; then
    rm -f $eventRequest

    echo -n "$1" > $eventRequest
fi

sync

pkill --signal SIGUSR1 -x vlcm-main

# Wait for 2m30s for output (the loop might increase that time a little bit).
for retry in $(seq 1 1500); do
    sync

    if [ -f $eventResponse ]; then
        ret=$(cat $eventResponse)

        if [ ".$ret" != "." ]; then
            break
        fi
    fi

    sleep 0.1s
done

rm -f $eventRequest
rm -f $eventResponse

if [ ".$ret" = "." ]; then
    echo "#error:No response"
    exit 254
fi

echo -n "$ret"
exit 0
