#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2013             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

def inv_if(info, params):
    def round_to_day(ts):
        broken = time.localtime(ts)
        return time.mktime((broken.tm_year, broken.tm_mon, broken.tm_mday, 0, 0, 0, broken.tm_wday, broken.tm_yday, broken.tm_isdst))

    now = time.time()

    port_info, uptime_info = info
    uptime = parse_snmp_uptime(uptime_info[0][0])

    usage_port_types = params.get("usage_port_types",
           [ '6', '32', '62', '117', '127', '128', '129', '180', '181', '182', '205', '229' ])
    unused_duration = params.get("unused_duration", 30 * 86400)

    def render_mac_address(bytestring):
        return ":".join(["%02s" % hex(ord(m))[2:] for m in bytestring]).replace(' ', '0').upper()

    total_ethernet_ports = 0
    available_ethernet_ports = 0

    node = inv_tree("networking.interfaces:")
    for if_index, if_descr, if_alias, if_type, if_speed, if_high_speed, \
        if_oper_status, if_admin_status, if_phys_address, if_last_change in port_info:

        if if_type in ( "231", "232" ):
            continue # Useless entries for "TenGigabitEthernet2/1/21--Uncontrolled"

        if not if_last_change or not if_speed:
            continue # Ignore useless half-empty tables (e.g. Viprinet-Router)

        # if_last_change can be of type Timeticks (100th of seconds) or
        # a human readable time stamp (yurks)
        try:
            last_change = float(if_last_change) / 100.0
        except:
            # Example: 0:0:01:09.96
            parts = if_last_change.split(":")
            days    = int(parts[0])
            hours   = int(parts[1])
            minutes = int(parts[2])
            seconds = float(parts[3])
            last_change = seconds + 60*minutes + 3600*hours + 86400*days

        if if_high_speed:
            speed = int(if_high_speed) * 1000 * 1000
        else:
            speed = int(if_speed)

        if last_change > 0:
            state_age = uptime - last_change
        else:
            # Assume point of time of boot as last state change.
            state_age = uptime

        last_change_timestamp = round_to_day(now - state_age)

        node.append({
            "index"        : int(if_index),
            "description"  : if_descr,
            "alias"        : if_alias,
            "speed"        : speed,
            "phys_address" : render_mac_address(if_phys_address),
            "oper_status"  : int(if_oper_status),
            "admin_status" : int(if_admin_status), # 1(up) or 2(down)
            "port_type"    : int(if_type),
            "last_change"  : int(last_change_timestamp),
        })


        if if_type in usage_port_types:
            if_available = if_oper_status == '2' and state_age > unused_duration
            total_ethernet_ports += 1
            if if_available:
                available_ethernet_ports += 1
            node[-1]["available"] = if_available
        else:
            if_available = None

    node = inv_tree("networking.")
    node["available_ethernet_ports"] = available_ethernet_ports
    node["total_ethernet_ports"] = total_ethernet_ports
    node["total_interfaces"] = len(info)

inv_info['inv_if'] = {
    "inv_function" : inv_if,
    'snmp_info': [
        ( ".1.3.6.1.2.1", [
           "2.2.1.1",            # ifIndex
           "2.2.1.2",            # ifDescr
           "31.1.1.1.18",        # ifAlias
           "2.2.1.3",            # ifType
           "2.2.1.5",            # ifSpeed
           "31.1.1.1.15",        # ifHighSpeed   .. 1000 means 1Gbit
           "2.2.1.8",            # ifOperStatus
           "2.2.1.7",            # ifAdminStatus
           "2.2.1.6",            # ifPhysAddress
           "2.2.1.9",            # ifLastChange
        ]),
        ( ".1.3.6.1.2.1.1", [ "3.0" ] ), # uptime
    ],
    'snmp_scan_function': lambda oid: int(oid(".1.3.6.1.2.1.2.1.0")) >= 2,
}
