#!/bin/sh
# ILM Highland Inventory Agent — Linux installation.
#
# Installs the official GLPI Agent 1.18 and writes the server address and tag
# straight away, so the machine appears in the inventory without anyone editing
# a configuration file afterwards.
#
#   curl -fsSL https://i1m.uk/downloads/linux/install-ilm-agent.sh | sudo sh
#
set -eu

SERVER="https://i1m.uk/front/inventory.php"
TAG="ilm"
BASE="https://i1m.uk/downloads/linux"
VER="1.18"

[ "$(id -u)" = "0" ] || { echo "Please run as root (sudo)." >&2; exit 1; }

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

if command -v apt-get >/dev/null 2>&1; then
    echo "Debian/Ubuntu detected: installing glpi-agent ${VER}"
    curl -fsSL -o "$TMP/glpi-agent.deb" "$BASE/glpi-agent_${VER}-1_all.deb"
    apt-get install -y "$TMP/glpi-agent.deb"
elif command -v dnf >/dev/null 2>&1; then
    echo "Fedora/RHEL detected: installing glpi-agent ${VER}"
    curl -fsSL -o "$TMP/glpi-agent.rpm" "$BASE/glpi-agent-${VER}-1.noarch.rpm"
    dnf install -y "$TMP/glpi-agent.rpm"
elif command -v yum >/dev/null 2>&1; then
    curl -fsSL -o "$TMP/glpi-agent.rpm" "$BASE/glpi-agent-${VER}-1.noarch.rpm"
    yum install -y "$TMP/glpi-agent.rpm"
else
    echo "No supported package manager found (apt, dnf or yum)." >&2
    exit 1
fi

CONF=/etc/glpi-agent/agent.cfg
mkdir -p "$(dirname "$CONF")"
# Set the server and tag without disturbing any other settings already present.
if [ -f "$CONF" ]; then
    sed -i "/^[#[:space:]]*server[[:space:]]*=/d;/^[#[:space:]]*tag[[:space:]]*=/d" "$CONF"
fi
{
    echo "server = $SERVER"
    echo "tag = $TAG"
} >> "$CONF"

systemctl enable --now glpi-agent 2>/dev/null || true
echo "Taking the first inventory..."
glpi-agent --force 2>/dev/null || /usr/bin/glpi-agent --force 2>/dev/null || true

echo "Done. This device will appear in the inventory within about a minute."
