#!/usr/bin/python
# Riptide SNMP upgrade script for pre-Riptide releases

import os
import sys

from isi.config import mxd
from isi.ui.lib.snmpd_config import SNMPDConfig

CONFIG_GROUPS = ['server', 'protocol_access', 'security']

SNMP_PARAM_NAMES = {'enable_v1_v2c'    : 'SNMP v1/v2c access',
                    'rocommunity'     : 'Read-only community',
                    'enable_v3'       : 'SNMP v3 access',
                    'rouser'          : 'Read-only user',
                    'auth_passphrase' : 'SNMP v3 password',
                    'syslocation'     : 'System location',
                    'syscontact'      : 'System contact'}

PROTOCOL_SNMP_V1_V2C = 0x01
PROTOCOL_SNMP_V3     = 0x02

default_file = '/etc/mcp/sys/snmpd.xml'
delta_file   = '/etc/mcp/override/snmpd.xml'


def str_to_boolean(bool_str):
    if bool_str == 'NO':
        return False
    if bool_str == 'YES':
        return True
    return bool_str

def main():
    snmp_config = SNMPDConfig()
    # if the old config doesn't exist, just return
    if os.path.isfile(default_file):
        root = mxd.loadmxd(default_file, delta_file).getroot()
    else:
        return 0

    # grab the snmp config values from the mcp xml files
    parameters = {}
    if root is not None:
        for g in CONFIG_GROUPS:
            confGroup = root.getchildnamed(g)
            for item in confGroup.getchildren():
                parameters[item.name()] = str_to_boolean(item.gettext())
    # if we actually got values
    if len(parameters) != 0:
        # set the values into gconfig
        protocol = 0
        if parameters['enable_v1_v2c']:
            protocol = protocol | PROTOCOL_SNMP_V1_V2C
        if parameters['enable_v3']:
            protocol = protocol | PROTOCOL_SNMP_V3
        snmp_config.set_protocols(protocol)
        snmp_config.set_auth_passphrase(parameters['auth_passphrase'])
        snmp_config.set_syslocation(parameters['syslocation'])
        snmp_config.set_syscontact(parameters['syscontact'])
        snmp_config.set_rocommunity(parameters['rocommunity'])
        snmp_config.set_rouser(parameters['rouser'])
        # save (and write out the new snmpd.config)
        snmp_config.save()
        os.remove(default_file)
        if os.path.exists(delta_file):
            os.remove(delta_file)

    return 0

if __name__ == '__main__':
    sys.exit(main())
