#!/usr/bin/python

'''
Small get Status of network devices
'''

# Some settings
VERSION         = '0.1'
# Nagios Exit Codes:
STATE_OK, STATE_WARNING, STATE_CRITICAL, STATE_UNKNOWN\
                = 0, 1, 2, 3

# Import modules
import sys
from optparse import OptionParser
from re import match
from os import path, environ
from subprocess import Popen, PIPE

def print_and_exit(message, errorcode):
    ''' Prints message and exit with Errocode given'''
    print(message)
    sys.exit(errorcode)

def get_network_devices():
    '''
    Execute "ip link show" and parse the output of stdout
    Dictonary you get is Dict[NameDevice][Value]
    Example:
            network_devices['eth0']['state'] = 'UP'
    '''
    # Make shure we got /sbin and /usr/sbin in $PATH
    # Some environments doesn't include them for users
    environ['PATH'] += ':/usr/sbin:/sbin'
    cmdline = 'ip link show'
    cmd = cmdline.split()
    try:
        process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True)
    except OSError:
        message = 'Couldn\'t execute "%s"' %(cmdline)
        print_and_exit(message, STATE_UNKNOWN)
    stdout, stderr = process.communicate()
    if not process.returncode == 0:
        message = 'Error executing "%s" - Error message "%s"' %(cmdline, stderr)
        print_and_exit(message, STATE_UNKNOWN)
    lines = stdout.split('\n')
    # Parse lines and search for network devices
    network_devices = {}
    for line in lines:
        if match('^[0-9]+:.*', line):
            line = line.split()
            device_name = line[1].split(':')[0]
            network_devices[device_name] = {}
            network_devices[device_name]['name'] = device_name
            network_devices[device_name]['flags'] = line[2][1:-1].split(',')
            # Cut it:
            line = line[3:]
            a = 0
            while a < len(line):
               if (a + 1) < len(line):
                   network_devices[device_name][line[a]] = line[a + 1]
               else:
                   network_devices[device_name][line[a]] = ""
               a += 2
    return network_devices

def check_network_device(network_device):
    '''
    Check if the state of a given network device is ok
    '''
    check_type = options.check_type
    if check_type == []:
        check_type = ['state:^UP$']
    for type in check_type:
        try:
            type, regex = type.split(':', 1)
        except ValueError:
            message = '"%s" seems not to be "TYPE:REGEX"' \
            % type
            print_and_exit(message, STATE_UNKNOWN)
        if not network_device.has_key(type):
            message = '"%s" not a valid type"' % type
            print_and_exit(message, STATE_UNKNOWN)
        if not match(regex, network_device[type]) :
            print_and_exit('network device "%s" value "%s" doesn\'t match "%s"'\
            % (network_device['name'], type, regex), STATE_CRITICAL)

def parse_arguments():    
    '''
    Parse the arguments given from commandline.
    '''
    parser = OptionParser(\
                      version="%%prog Version %s" % (VERSION),\
                      usage="%prog [-d DEVICE|-e DEVICE]\nExample: %prog -t 'state:^UP$' -t 'mtu:^1500$' -e lo -e tun0")
    parser.add_option('-t', \
                      '--type', \
                      action = 'append', \
                      dest='check_type', \
                      type='str', \
                      help = 'Type you want to be checked. \
                      Default is "state:^UP$" this is a value checked against a regex. \
                                     Example: "mtu:^1500$" \
                                     Multiple Values possible' , \
                      default = [])
    parser.add_option('-e', \
                      '--exclude', \
                      action = 'append', \
                      dest='exclude_devices', \
                      type='str', \
                      help = 'Exclude these devices. Multiple Values possible',\
                      default = [])
    parser.add_option('-d', \
                      '--device', \
                      action = 'store', \
                      dest='network_device', \
                      type='str', \
                      help = 'network device number to check. \
                      Normaly all devices found will be checked', \
                      default = None)
    global options, args
    (options, args) = parser.parse_args()
    if options.exclude_devices != [] and options.network_device:
        print_and_exit('-d or -e should be present.', STATE_UNKNOWN)

def main():
    '''
    Here is where the pepper grows...
    '''
    # Parse arguments given
    parse_arguments()
    # First get all Devices:
    devices = get_network_devices()
    # If we have no devices given by commandline
    if options.network_device:
        if not devices.has_key(str(options.network_device)):
            print_and_exit(\
            'No network device "%s" found|' % (options.network_device), STATE_UNKNOWN)
        devicename = options.network_device
        check_network_device(devices[devicename])
    else:
        checked_devices = ''
        for devicename in devices:
            if devicename not in options.exclude_devices:
                check_network_device(devices[devicename])
                checked_devices += '%s ' % devicename
        print_and_exit('Network devices " %s" are ok' % checked_devices, STATE_OK)
    print_and_exit('Network device "%s" is ok' % (devices[devicename]['name']), STATE_OK)

main()
