#coding:utf-8

import os
import sys
import sunhpc
import shutil
import textwrap
import subprocess
class Command(sunhpc.commands.pxelinux.build.command):
    """
    Build the dhcp service for the sunhpc cluster.

    <param type='Bool' name='Quiet'>
    Whether to output detailed information, default: no
    </param>
    
    <example cmd='pxelinux build dhcpd'>
    In local build the dhcp service.
    </example>

    <example cmd='pxelinux build dhcpd'>
    Build the dhcp service.
    </example>
    """
    def run(self, params, args):

        (quiet, ) = self.fillParams([('quiet', 'no')])

        q = self.str2bool(quiet)
        self.msg('Starting build the dhcpd service...', q=q)

        # install dhcp server
        self.installDhcpd(q)

    def installDhcpd(self, q):
        config = '/etc/dhcp/dhcpd.conf'

        # The dhcpd is not installed.
        if not os.path.exists(config):
            self.shcmd('yum install -y dhcp dhcp-common dhcp-libs --enablerepo=Sunhpc-%s' % sunhpc.version)

        self.fw.addports(['67'], ['udp'])

        os.system('sunhpc report host dhcpd > %s' % config)

        dhcpd_srv_conf = '/usr/lib/systemd/system/dhcpd.service'
        with open(dhcpd_srv_conf, 'w') as f:
            f.write(textwrap.dedent("""\
                [Unit]
                Description=DHCPv4 Server Daemon
                Documentation=man:dhcpd(8) man:dhcpd.conf(5)
                Wants=network-online.target
                After=network-online.target
                After=time-sync.target

                [Service]
                Type=notify
                ExecStart=/usr/sbin/dhcpd -f -cf /etc/dhcp/dhcpd.conf -user dhcpd -group dhcpd --no-pid %s

                [Install]
                WantedBy=multi-user.target
            """ % devices))

        self.shcmd('systemctl daemon-reload')
        self.shcmd('systemctl stop dhcpd')
        self.shcmd('systemctl start dhcpd')
        self.shcmd('systemctl enable dhcpd')

RollName = "base"
