from __future__ import print_function

import re

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent
from .mgnt_auto_checkout_test import AutoCheckoutTest


class DHCPConfTest(AutoCheckoutTest):
    test_id = 'dhcp_conf'
    description = 'Found in dhcpd.conf'
    read_only = True
    deferred = False

    def __init__(self):
        super(DHCPConfTest, self).__init__(
            pre_checkout_routines=[]
        )
        self.dhcp_conf_path = '$DHCP/dhcpd.conf'
        self.pattern_template = r'^\s*host\s+{}\s*(?:{{\s*)?$'

    def execute(self, magnet):
        if magnet['psc_type'] != 'EMCOR':
            self.status = None
            return

        psc_node = 'cpu-{}-mg{}'.format(magnet['loca'].lower(), magnet['crate_num'].zfill(2))
        host_pattern = self.pattern_template.format(re.escape(psc_node))
        host_pattern_re = re.compile(host_pattern)
        agent = FacilityAgent(utilities.facility)
        dhcp_conf_content = agent.read_file(self.dhcp_conf_path)
        for line in dhcp_conf_content.splitlines():
            line_str = line.decode('utf-8')
            if host_pattern_re.match(line_str):
                self.data = line_str
                self.status = True
                print('PASS')
                return

        self.data = '{} not found in dhcpd.conf'.format(psc_node)
        self.status = False
        print('FAIL')
