#!/bin/bash
echo "============================================="
echo "  1Acces Print Collector Agent - Installation"
echo "============================================="
echo ""

# Verifier root
if [ "$EUID" -ne 0 ]; then
    echo "[ERREUR] Veuillez executer ce script en tant que root (sudo)"
    exit 1
fi

INSTALL_DIR="/opt/1acces/print-agent"

# 1. Creer le dossier
echo "[1/5] Creation du dossier $INSTALL_DIR..."
mkdir -p "$INSTALL_DIR"

# 2. Copier l'executable
echo "[2/5] Copie de l'agent..."
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cp "$SCRIPT_DIR/print-agent-linux-x64" "$INSTALL_DIR/" 2>/dev/null || true
chmod +x "$INSTALL_DIR/print-agent-linux-x64"

# 3. Generer config
echo "[3/5] Generation de la configuration..."
if [ ! -f "$INSTALL_DIR/config.json" ]; then
    cat > "$INSTALL_DIR/config.json" << 'CONF'
{
  "apiUrl": "https://erp-pme-api.onrender.com/api/printing",
  "agentKey": "",
  "agentId": "",
  "agentName": "Agent Linux",
  "pollIntervalMinutes": 15,
  "snmpCommunity": "public",
  "snmpTimeout": 5000,
  "networkRange": "192.168.1.0/24",
  "printerIps": []
}
CONF
fi

# 4. Creer le service systemd
echo "[4/5] Installation du service systemd..."
cat > /etc/systemd/system/1acces-print-agent.service << EOF
[Unit]
Description=1Acces Print Collector Agent
After=network.target

[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/print-agent-linux-x64
Restart=always
RestartSec=30
User=root
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable 1acces-print-agent

# 5. Afficher les instructions
echo "[5/5] Installation terminee !"
echo ""
echo "============================================="
echo "  CONFIGURATION REQUISE"
echo "============================================="
echo ""
echo "  1. Ouvrez https://erp.1acces.com"
echo "  2. Gestion Impression > Agents > Nouvel agent"
echo "  3. Copiez l'Agent ID et l'Agent Key"
echo "  4. Editez $INSTALL_DIR/config.json"
echo "     sudo nano $INSTALL_DIR/config.json"
echo "  5. Collez agentKey et agentId"
echo "  6. Demarrez le service :"
echo "     sudo systemctl start 1acces-print-agent"
echo ""
echo "  Commandes utiles :"
echo "     sudo systemctl status 1acces-print-agent"
echo "     sudo journalctl -u 1acces-print-agent -f"
echo ""
echo "============================================="
