#!/usr/bin/env python2.6
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2011 Citrix Systems, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import sys
import logging

from geppetto.hapi import interface, config_util
from geppetto.hapi import exception
from geppetto import hapi

logger = logging.getLogger('vif-update')

IFCFG_BASE = '/etc/sysconfig/network-scripts/ifcfg-%s'


if __name__ == "__main__":
    try:
        # Assuming a device in the form ethXX where XX is a number has
        # been passed on the command line
        device = sys.argv[1]
        if not device:
            logger.exception("No device found on the command line. Aborting.")
            sys.exit(2)
        
        device_name = sys.argv[1]
        device_id = device_name[3:]
        
        config = config_util.parse_config(IFCFG_BASE %device_name)
        net = config_util.config_get(config,
                                     'GEPPETTO_HOST_NETWORK',
                                     '')
        # Yet another hack
        if net == 'NO_NET':
            logger.debug("Network should not be created")
            sys.exit(0)
    
        on_boot = config_util.config_get(config,
                                         'ONBOOT',
                                         '')
        ethX_is_off = on_boot == "no"
        session = interface.Session.createSession()
        session.login()
        ethX_vif = session.Network.find_vif(device=device_id)
        if ethX_vif == None:
            if ethX_is_off:
                logger.debug('VIF not added')
            else:
                session.Network.add_vif(net, device=device_id)
                logger.debug('Added a new VIF')
        else:
            # if required
            if net == '':
                logger.warning('VIF found on %s, but no network '
                               'component found: nothing to do.' % device_name)
                sys.exit(0)
            vif_network_dict = \
                    session.Network.get_network_dict_by_vif(ethX_vif)
            network_dict = session.Network.get_network_dict_by_component(net)
            if not ethX_is_off and \
                session.Network.compare_networks(vif_network_dict,
                                                 network_dict):
                logger.debug('VIF already correctly configured')
            else:
                # destroy existing vif and attach updated one
                session.Network.delete_vif(ethX_vif)
                if ethX_is_off:
                    logger.debug('VIF removed')
                else:
                    session.Network.add_vif(net, device=device_id)
                    logger.debug('Added a new VIF')
    except exception.HAPIFailure, e:
        logger.exception('Failure: exit_code(%s), message(%s)' \
                                                    % (e.code, e.message))
        if e.inner:
            logger.exception('Inner failure: %s' % e.inner)
        sys.exit(1)
