#coding:utf-8

import os
import sys
import sunhpc.commands
class Plugin(sunhpc.commands.Plugin):

    def getFilename(self, nodeid):
        nrows = self.db.search("""select networks.ip from
            networks,subnets where
            networks.node = %s and subnets.name = "private" and
            networks.subnet = subnets.id
            """ % (nodeid))

        if nrows < 1:
            return None

        ipaddr, = self.db.fetchone()

        filename = '/tftpboot/pxelinux/pxelinux.cfg/'
        for i in ipaddr.split('.'):
            hexstr = '%02x' % (int(i))
            filename += '%s' % hexstr.upper()
        return filename

    def writeDefaultPxebootCfg(self):
        nrows = self.db.search("select kernel, ramdisk, args from bootactions where action='install'")
        if nrows == 1:
            kernel, ramdisk, args = self.db.fetchone()

            filename = '/tftpboot/pxelinux/pxelinux.cfg/default'
            file = open(filename, 'w')
            file.write('default sunhpc\n')
            file.write('prompt 0\n')
            file.write('label sunhpc\n')

            if len(kernel) > 6 and kernel[0:7] == 'vmlinuz':
                file.write('\tkernel %s\n' % (kernel))
            if len(ramdisk) > 0:
                if len(args) > 0:
                    args += ' initrd=%s' % ramdisk
                else:
                    args = 'initrd=%s' % ramdisk
            if len(args) > 0:
                file.write('\tappend %s\n' % (args))

            file.close()

            #
            # make sure apache can update the file
            #
            os.system('chown root.apache %s' % (filename))
            os.system('chmod 664 %s' % (filename))


    def writePxebootCfg(self, node, nodeid):
        #
        # there is a case where the host name may be in the nodes table
        # but not in the boot table. in this case, remove the current
        # configuration file (if it exists) and return
        #
        filename = self.getFilename(nodeid)

        nrows = self.db.search("select status from nodes where id = %s" % nodeid)
        if nrows < 1:
            if filename != None and os.path.exists(filename):
                os.unlink(filename)
            return
        else:
            action, = self.db.fetchone()

        #
        # get the bootaction from the 'installaction' or
        # 'runaction' column
        #
        if action in [ 'os', 'install' ]:
            nrows = self.db.search("select status from nodes where name = '%s'" % node)
        else:
            print ('action "%s" for host "%s" is invalid' % (action, node))
            sys.exit(-1)

        if nrows == 1:
            bootaction, = self.db.fetchone()
        else:
            print ('failed to get bootaction')
            sys.exit(-1)

        nrows = self.db.search("""select kernel, ramdisk, args from
            bootactions where action = '%s' """% bootaction)

        if nrows == 1:
            kernel, ramdisk, args = self.db.fetchone()
        else:
            print ('bootaction "%s" for host "%s" is invalid' % (action, node))
            sys.exit(-1)

        if args and args.find('ksdevice=') != -1:
            self.db.execute("""select net.ip
                from networks net, subnets s, nodes n
                where n.name='%s' and net.node=n.id and
                s.id=net.subnet and s.name='private' and
                net.ip is not NULL""" % node)
            ip, = self.db.fetchone()
            args += ' ip=%s ' % ip
            attrs = self.db.getHostAttrs('localhost')
            # hostname=%s
            args += 'gateway=%s netmask=%s dns=%s nextserver=%s'%(\
                attrs['Kickstart_PrivateGateway'],
                attrs['Kickstart_PrivateNetmask'],
                attrs['Kickstart_PrivateDNSServer'],
                attrs['Kickstart_PrivateAddress'])

        if args and args.find('inst.ks=') == -1:
            address  = self.db.getHostAttr('localhost', 'Kickstart_PrivateAddress')
            args += ' inst.ks=http://%s/install/sbin/kickstart.cgi' % address

        if filename != None:
            file = open(filename, 'w')  
            file.write('default sunhpc\n')
            file.write('prompt 0\n')
            file.write('label sunhpc\n')

            if kernel:
                if kernel[0:7] == 'vmlinuz':
                    file.write('\tkernel %s\n' % (kernel))
                else:
                    file.write('\t%s\n' % (kernel))

            if ramdisk and len(ramdisk) > 0:
                if len(args) > 0:
                    args += ' initrd=%s' % ramdisk
                else:
                    args = 'initrd=%s' % ramdisk

            if args and len(args) > 0:
                file.write('\tappend %s\n' % (args))

            # If using ksdevice=bootif we need to
            # pass the PXE information to loader.
            
            if args and args.find('bootif') != -1:
                file.write('\tipappend 2\n')

            file.close()

            #
            # make sure apache can update the file
            #
            os.system('chown root.apache %s' % (filename))
            os.system('chmod 664 %s' % (filename))

    def run(self, host):
        nrows = self.db.search("select id from nodes where name = '%s'" % host)
        if nrows > 0:
            nodeid, = self.db.fetchone()
        else:
            print ('could not find host "%s" in the database' % host)
            sys.exit(-1)

        frontend_host = self.db.getHostAttr('localhost', 'Kickstart_PrivateHostname')

        if host == frontend_host:
            self.writeDefaultPxebootCfg()
        else:
            self.writePxebootCfg(host, nodeid)

    def __repr__(self):
        return '01'

RollName = "base"
