#!/bin/bash

# Paramètres
LIVEBOX_IP="192.168.1.1"
USERNAME="admin"
PASSWORD="HYJcanGE"  # Change avec ton vrai mot de passe
CURL_OPTS="-s"

# 1️⃣ Authentification - obtenir le contextID
CONTEXT_ID=$(curl $CURL_OPTS -X POST "http://$LIVEBOX_IP/ws" \
    -H "Content-Type: application/x-sah-ws-4-call+json" \
    -H "Authorization: X-Sah-Login" \
    -d "{
        \"service\": \"sah.Device.Information\",
        \"method\": \"createContext\",
        \"parameters\": {
            \"applicationName\": \"curl\",
            \"username\": \"$USERNAME\",
            \"password\": \"$PASSWORD\"
        }
    }" | jq -r '.data.contextID')

if [ -z "$CONTEXT_ID" ] || [ "$CONTEXT_ID" == "null" ]; then
    echo "❌ Erreur d'authentification"
    exit 1
fi

# 2️⃣ Récupération de la liste des équipements connectés
DEVICE_LIST=$(curl $CURL_OPTS -X POST "http://$LIVEBOX_IP/ws" \
    -H "Content-Type: application/x-sah-ws-4-call+json" \
    -H "X-Context: $CONTEXT_ID" \
    -d '{
        "service": "NeMo.Intf.lan",
        "method": "getMIBs",
        "parameters": {
            "mibs": "dhcp_leases"
        }
    }')

# 3️⃣ Extraction et affichage propre
echo "📡 Appareils connectés :"
echo "$DEVICE_LIST" | jq -r '.data.dhcp_leases[] | "\(.IPAddress) - \(.HostName) - \(.MACAddress)"'

# Optionnel : déconnexion propre (fermeture de la session)
curl $CURL_OPTS -X POST "http://$LIVEBOX_IP/ws" \
    -H "Content-Type: application/x-sah-ws-4-call+json" \
    -H "X-Context: $CONTEXT_ID" \
    -d '{
        "service": "sah.Device.Information",
        "method": "releaseContext",
        "parameters": {}
    }' > /dev/null


