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

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

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

# 2. Generer config
echo "[2/4] 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 macOS",
  "pollIntervalMinutes": 15,
  "snmpCommunity": "public",
  "snmpTimeout": 5000,
  "networkRange": "192.168.1.0/24",
  "printerIps": []
}
CONF
fi

# 3. Creer le service launchd
echo "[3/4] Installation du service launchd..."
cat > ~/Library/LaunchAgents/com.1acces.print-agent.plist << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.1acces.print-agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>/opt/1acces/print-agent/print-agent-macos-arm64</string>
    </array>
    <key>WorkingDirectory</key>
    <string>/opt/1acces/print-agent</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/opt/1acces/print-agent/agent.log</string>
    <key>StandardErrorPath</key>
    <string>/opt/1acces/print-agent/agent-error.log</string>
</dict>
</plist>
EOF

echo "[4/4] 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 "  5. Placez l'executable dans $INSTALL_DIR/"
echo "  6. Demarrez le service :"
echo "     launchctl load ~/Library/LaunchAgents/com.1acces.print-agent.plist"
echo ""
echo "============================================="
