#!/bin/sh

# This is the 'finish' script for the te-inventory-agent runit service.
# It is executed by runit whenever the supervised process (te-inventory-agent) exits.
# This script receives two arguments from runit: RUNSV_STATUS and PROCESS_STATUS.

RUNSV_STATUS=$1
PROCESS_STATUS=$2

if [ "$RUNSV_STATUS" -ne 0 ]; then
    # Check the actual exit status of the te-inventory-agent process.
    if [ "$PROCESS_STATUS" -eq 143 ]; then # SIGTERM (128+15)
        # Clean exit: The agent received a SIGTERM signal and shut down gracefully.
        # This is typically what happens when the service is stopped via 'sv stop'.
        echo "te-inventory-agent exited on SIGTERM." 
    else
        # Non-clean exit: The agent exited with an unexpected code or was killed by another signal.
        # This could indicate a crash, an unhandled error, or an external kill signal.
        echo "te-inventory-agent exited with code ${PROCESS_STATUS}. Sleeping 30 seconds."
        sleep 30
    fi
fi
