#! /usr/bin/python
#
# Copyright 2011-2012 Red Hat, Inc.
#
# This program 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; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#

import logging
import logging.config

from netconf import ifcfg
from vdsm.config import config
from vdsm.netconfpersistence import RunningConfig, PersistentConfig
from configNetwork import setupNetworks, ConfiguratorClass


def ifcfg_restoration():
    configWriter = ifcfg.ConfigWriter()
    configWriter.restorePersistentBackup()


def unified_restoration():
    """
    Builds a setupNetworks command from the persistent configuration to set it
    as running configuration.
    """
    configurator = ConfiguratorClass()
    runningConfig = RunningConfig()
    removeNetworks = {}
    removeBonds = {}
    for network in runningConfig.networks:
        removeNetworks[network] = {'remove': True}
    for bond in runningConfig.bonds:
        removeBonds[bond] = {'remove': True}
    logging.debug('Removing all networks (%s) and bonds (%s) in running '
                  'config.', removeNetworks, removeBonds)
    setupNetworks(removeNetworks, removeBonds, connectivityCheck=False,
                  _inRollback=True)

    configurator.flush()
    persistentConfig = PersistentConfig()
    nets = persistentConfig.networks
    bonds = persistentConfig.bonds
    logging.debug('Calling setupNetworks with networks (%s) and bond (%s).',
                  nets, bonds)
    setupNetworks(nets, bonds, connectivityCheck=False, _inRollback=True)


def restore():
    if config.get('vars', 'net_persistence') == 'unified':
        unified_restoration()
    else:
        ifcfg_restoration()


if __name__ == '__main__':
    try:
        logging.config.fileConfig('/etc/vdsm/svdsm.logger.conf',
                                  disable_existing_loggers=False)
    except:
        logging.basicConfig(filename='/dev/stdout', filemode='w+',
                            level=logging.DEBUG)
        logging.error('Could not init proper logging', exc_info=True)

    restore()
