#!/bin/bash
#
####################################################################
# Fusion Producer daemon upgrade
####################################################################
# Copyright (c) 2026 Nagios Enterprises, LLC. All rights reserved.
####################################################################
#
. ../../xi-sys.cfg

BIN_SRC="fusion-producer"
BIN_DST="/usr/local/bin/fusion-producer"
UNIT_DST="/usr/lib/systemd/system/fusion-producer.service"
UNIT_SRC="./fusion-producer.service"

if [ ! -f "$BIN_SRC" ]; then
	echo "WARNING: $BIN_SRC not found — nothing to upgrade."
	exit 0
fi

if [ ! -f "$BIN_DST" ]; then
	echo "INFO: No installed version found at $BIN_DST — performing install instead of upgrade."
	cp -f "$BIN_SRC" "$BIN_DST"
	chmod 755 "$BIN_DST"
	echo "UPGRADE: Installed new binary to $BIN_DST."
	exit 0
fi

if cmp -s "$BIN_SRC" "$BIN_DST"; then
	echo "SKIP: $BIN_SRC matches installed binary — no upgrade needed."
	exit 0
fi

echo "UPGRADE: New version detected in $BIN_SRC. Copying to $BIN_DST..."
cp -f "$BIN_SRC" "$BIN_DST"
chown "$apacheuser:$nagiosgroup" "$BIN_DST"
chmod 755 "$BIN_DST"
#
# Install files service and toml if necessary    
if [ ! -d /etc/fusion ] ; then 
        mkdir -p /etc/fusion
        chown "root:$apachegroup" /etc/fusion
        chmod 775 /etc/fusion
        cp fusion-producer.toml.example /etc/fusion/fusion-producer.toml
        chown "$apacheuser:$nagiosgroup" /etc/fusion/fusion-producer.toml
        chmod 770 /etc/fusion/fusion-producer.toml
fi 

if [ ! -f "$UNIT_DST" ] ; then 
        install -m 644 -o root -g root "$UNIT_SRC" "$UNIT_DST"
	if command -v systemctl >/dev/null 2>&1; then
        	systemctl daemon-reload
        	systemctl disable fusion-producer.service 2>/dev/null || true
	fi

fi

# Determine service state before any changes
STATE="inactive"
if command -v systemctl >/dev/null 2>&1; then
	STATE=$(systemctl is-active fusion-producer.service 2>/dev/null || echo "inactive")
fi

if [ "$STATE" = "active" ]; then
	echo "UPGRADE: Stopping running service before copy."
	systemctl stop fusion-producer.service
fi

echo "UPGRADE: Binary copied to $BIN_DST."

if [ "$STATE" = "active" ]; then
	echo "UPGRADE: Restarting service."
	systemctl start fusion-producer.service || \
		echo "WARNING: fusion-producer.service failed to restart."
else
	echo "UPGRADE: Service was not running ($STATE), skipped restart."
fi
