#coding:utf-8

import sunhpc
import sqlalchemy
from sunhpc.db.mappings.base import *
class command(sunhpc.commands.HostArgumentProcessor,
        sunhpc.commands.report.command):
    pass

class Command(command):
    """
    Report the next available IP address on the given subnet

    <arg type='string' name='subnet'>
    The subnet name that we should use
    </arg>

    <param type='int' name='increment'>
    The increment that should be used to find the next available IP
    Default to -1
        </param>

    <param type='string' name='baseip'>
    The starting IP address we should use to generate IPs
        </param>

    <example cmd='report nextip private'>
    Output the next available IP on the private subnet
    </example>
    """

    def run(self, param, args):

        (increment, baseip) = self.fillParams( [
            ('increment', '-1'), 
            ('baseip', '')
            ])

        if len(args) != 1:
            self.abort('must supply the subnet')

        increment = int(increment)

        subnet = args[0]
        
        try:            
            subnet_db = self.newdb.getSession().query(sunhpc.db.mappings.base.Subnet)\
                .options(sqlalchemy.orm.joinedload('networks'))\
                .filter(Subnet.name == subnet).one()
        except sqlalchemy.orm.exc.NoResultFound:
            self.abort('subnet %s is not valid' % subnet)

        mask_ip     = sunhpc.core.ip.IPAddr(subnet_db.netmask)
        network_ip  = sunhpc.core.ip.IPAddr(subnet_db.subnet)
        bcast_ip    = sunhpc.core.ip.IPAddr(network_ip | sunhpc.core.ip.IPAddr(~mask_ip))
        bcast       = "%s" % (bcast_ip)
        used_ip     = [ net.ip for net in subnet_db.networks]
        
        ip = sunhpc.core.ip.IPGenerator(bcast, subnet_db.netmask)
        if baseip:
            ip.addr = sunhpc.core.ip.IPAddr(baseip)

        while 1:
            nextip = ip.next(increment)
            if str(nextip) not in used_ip:
                # we found it
                break

        self.beginOutput()
        self.addOutput('localhost', nextip)
        self.endOutput(padChar='')

RollName = "base"
