<?php

echo(" Iskratel BIP8 Discovery ");

$base_oid = '1.3.6.1.4.1.1332.1.1.5.3.112.4.1.7';
$base_oid_dot = '.' . $base_oid;
$sensor_type = 'ISKRATEL-MSAN-MIB-msanOltOnuPortStatInBip8Errors';

$bip8_array = snmpwalk_cache_oid($device, $base_oid, array());
$ifname_array = snmpwalk_cache_oid($device, 'ifName', array(), 'IF-MIB');

foreach ($bip8_array as $raw_index => $entry)
{
    $value = NULL;

    if (is_array($entry)) {
        foreach ($entry as $k => $v) {
            if (is_numeric($v)) {
                $value = $v;
                break;
            }
        }
    } elseif (is_numeric($entry)) {
        $value = $entry;
    }

    if (!is_numeric($value)) { continue; }

    // Observium may return the array index as:
    // 930
    // .1.3.6.1.4.1.1332.1.1.5.3.112.4.1.7.930
    // 1.3.6.1.4.1.1332.1.1.5.3.112.4.1.7.930
    // 3.6.1.4.1.1332.1.1.5.3.112.4.1.7.930
    $index = (string)$raw_index;
    $index = preg_replace('/^\./', '', $index);
    $index = preg_replace('/^iso\./', '', $index);
    $index = preg_replace('/^1\.3\.6\.1\.4\.1\.1332\.1\.1\.5\.3\.112\.4\.1\.7\./', '', $index);
    $index = preg_replace('/^3\.6\.1\.4\.1\.1332\.1\.1\.5\.3\.112\.4\.1\.7\./', '', $index);

    if (isset($ifname_array[$index]['ifName']) && $ifname_array[$index]['ifName'] != '') {
        $ifname = $ifname_array[$index]['ifName'];
    } else {
        $ifname = $index;
    }

    $descr = 'BIP8 ' . $ifname;

    $options = array(
        'sensor_type' => $sensor_type
    );

    discover_sensor(
        'gauge',
        $device,
        $base_oid_dot . '.' . $index,
        $index,
        $sensor_type,
        $descr,
        1,
        $value,
        $options
    );
}
