#!/bin/bash -e
#
####################################################################
# Fusion Producer daemon installation
####################################################################
# Copyright (c) 2026 Nagios Enterprises, LLC. All rights reserved.
####################################################################
#

. ../../xi-sys.cfg

echo "INSTALL: Fusion Producer is being installed..."

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

if [ ! -f "$BIN_SRC" ]; then
	echo "WARNING: $BIN_SRC not found — skipping Fusion Producer install (binary not yet provided)."
	exit 0
fi

if [ ! -f "$UNIT_SRC" ]; then
	echo "ERROR: $UNIT_SRC not found"
	exit 1
fi

install -m 755 -o root -g root "$BIN_SRC" "$BIN_DST"
chown "$apacheuser:$nagiosgroup" "$BIN_DST"
chmod 755 "$BIN_DST"

install -m 644 -o root -g root "$UNIT_SRC" "$UNIT_DST"

# Create config directory
mkdir -p /etc/fusion
chown "root:$apachegroup" /etc/fusion
chmod 775 /etc/fusion

# Install config file
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

# Ensure runtime directory exists for the Unix socket before first start
mkdir -p /run/fusion-producer
chown "$nagiosuser:$nagiosgroup" /run/fusion-producer
chmod 755 /run/fusion-producer

if command -v systemctl >/dev/null 2>&1; then
	systemctl daemon-reload
	systemctl disable fusion-producer.service 2>/dev/null || true
fi

# Sanity check
if [ ! -f "$BIN_DST" ]; then
	echo "ERROR: Fusion Producer install appears to have failed - exiting. Missing file = $BIN_DST"
	exit 1
fi

echo "INSTALL: Fusion Producer installed OK."
