#!/bin/bash
# SysAdmin LAN Agent (Linux)
SERVER_URL="https://ip.pietrolazzaro.com/index.php?api=agent_sync"
SUBNET=$(ip -4 route | grep -oP '192\.168\.[0-9]+|10\.[0-9]+\.[0-9]+|172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+' | head -1)
if [ -z "$SUBNET" ]; then SUBNET="192.168.0"; fi
echo "Scansione $SUBNET.0/24 in corso..."
for i in {1..254}; do ping -c 1 -W 1 $SUBNET.$i >/dev/null 2>&1 & done
wait
sleep 2
JSON="{\"subnet\": \"$SUBNET.0/24\", \"devices\": ["
FIRST=1
while read -r ip mac; do
  host="SCONOSCIUTO"
  if command -v nmblookup &> /dev/null; then res=$(nmblookup -A $ip 2>/dev/null | grep '<00> -         B <ACTIVE>' | head -1 | awk '{print $1}'); if [ ! -z "$res" ] && [ "$res" != "__MSBROWSE__" ]; then host=$res; fi; fi
  if [ $FIRST -eq 0 ]; then JSON="$JSON,"; fi
  JSON="$JSON{\"ip\": \"$ip\", \"mac\": \"${mac^^}\", \"host\": \"$host\"}"
  FIRST=0
done < <(ip neigh show | grep "lladdr" | grep " $SUBNET." | awk '{print $1 " " $5}')
JSON="$JSON]}"
curl -s -X POST -H "Content-Type: application/json" -d "$JSON" "$SERVER_URL"
echo "\n[+] Dati inviati al server SysAdmin remoto!"
