#!/usr/bin/env bash
set -e

BINARY="$(dirname "$0")/../agent/target/release/nanometrics-agent"
SERVICE="$(dirname "$0")/nanometrics-agent.service"
CONFIG="$(dirname "$0")/../agent/config.toml"

# Vérifications
if [ ! -f "$BINARY" ]; then
    echo "ERREUR : binaire introuvable : $BINARY"
    echo "Compilez d'abord : cargo build --release --manifest-path agent/Cargo.toml"
    exit 1
fi
if [ ! -f "$CONFIG" ]; then
    echo "ERREUR : config.toml introuvable : $CONFIG"
    echo "Copiez agent/config.toml.example vers agent/config.toml et ajustez l'IP du serveur."
    exit 1
fi

echo "[1/5] Copie du binaire vers /usr/local/bin/"
cp "$BINARY" /usr/local/bin/nanometrics-agent
chmod 755 /usr/local/bin/nanometrics-agent

echo "[2/5] Création du répertoire de configuration /etc/nanometrics/"
mkdir -p /etc/nanometrics
chmod 755 /etc/nanometrics

echo "[3/5] Copie de config.toml vers /etc/nanometrics/"
cp "$CONFIG" /etc/nanometrics/config.toml
chmod 644 /etc/nanometrics/config.toml

echo "[4/5] Installation du service systemd"
cp "$SERVICE" /etc/systemd/system/nanometrics-agent.service
systemctl daemon-reload
systemctl enable nanometrics-agent

echo "[5/5] Démarrage du service"
systemctl restart nanometrics-agent

sleep 2
echo ""
echo "=== Statut ==="
systemctl status nanometrics-agent --no-pager
