# -*- coding: utf-8 -*-
# Copyright (C) 2008-2009  Warp Networks, S.L.
# Author:  Pablo Martí
#
# 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.

import os

from twisted.python import log

from wader.common.utils import get_file_data, save_file


class NamedManager(object):

    def __init__(self, resolvconf_path='/etc/resolv.conf'):
        self.resolvconf_path = resolvconf_path
        self.old_contents = None

    def add_dns_info(self, dns):
        if self.old_contents is not None:
            # just log it, don't fail
            msg = "NamedManager old_contents not empty: %s"
            log.err(msg % self.old_contents)
            return

        # backup old data
        real_path = os.path.realpath(self.resolvconf_path)
        self.old_contents = get_file_data(real_path)
        # set new DNS data
        to_write = []
        if dns:
            to_write.append("# Generated by Wader")
            for d in dns:
                to_write.append("nameserver %s" % d)
            to_write.append('')

        save_file(real_path, '\n'.join(to_write))

    def delete_dns_info(self, dns):
        if self.old_contents is None:
            # just log it, don't fail
            log.err("NamedManager old_contents is None")
            return

        real_path = os.path.realpath(self.resolvconf_path)
        save_file(real_path, self.old_contents)
        self.old_contents = None
