# -*- mode: python; -*-
from invirt.database import models, connect
from invirt.config import structs as config
import re

connect()
prefix = "d_"

# 'machine_name', and optionally 'cdrom_image', should get passed in
# from the xm create call

def check(b):
    if not b:
        import sys
        sys.exit(1)

machine = models.Machine.query().filter_by(name=machine_name).one()
check(machine is not None)
machine_type = machine.type
cdrom = None
if 'cdrom_image' in locals():
    cdrom = models.CDROM.query().filter_by(cdrom_id=cdrom_image).one()
    check(cdrom is not None)

memory = machine.memory
maxmem = '2048'
check(re.match('^[A-Za-z0-9][A-Za-z0-9._-]*$', machine.name))
name = prefix + machine.name
check(re.match('^[0-9a-f-]+$', machine.uuid))
uuid = machine.uuid

vcpus = machine.cpus

diskioemu = ""
viftype = ""

pae = machine_type.pae
acpi = machine_type.acpi
apic = machine_type.apic

vif = []

disk = []

if machine_type.hvm:
    codepath = 'hvm'
else:
    codepath = 'paravm'

if 'installer_options' in locals(): #Installer
    import shlex
    install = dict(x.split("=",1) for x in shlex.split(installer_options))
    if 'preseed' in install: # d-i based installer
        baseurl = install['mirror']+"/dists/"+install['dist']+"/main/installer-"+install['arch']+"/current/images"
        kernelurl = baseurl + "/netboot/xen/vmlinuz"
        ramdiskurl = baseurl + "/netboot/xen/initrd.gz"

        import urllib
        class MyUrlOpener(urllib.FancyURLopener):
            def http_error_default(self, req, fp, code, msg, hdrs):
                raise IOError("%s %s" % (code, msg))
        urlopener = MyUrlOpener()

        try:
            print "Fetching %s" % kernelurl
            kernel, _ = urlopener.retrieve(kernelurl)
            print "Fetching %s" % ramdiskurl
            ramdisk, _ = urlopener.retrieve(ramdiskurl)
        except IOError, _:
            raise

        # For debugging, add "DEBCONF_DEBUG=5" to the arguments.
        extras = ["auto=true",
                  "debconf/priority=critical",
                  "debian-installer/locale=en_US.UTF-8",
                  "debian-installer/exit/always_halt=true",
                  "url="+install['preseed'],
                  "--", "console=hvc0"]

        extra = str.join(" ", extras)
    else: # Traditional debootstrap-based install
        disk.append('phy:/dev/xenvg/s_install_hda,hdb,r')

        import os
        release = os.uname()[2]
        kernel = '/boot/vmlinuz-%s' % release
        ramdisk = '/boot/initrd.img-%s' % release

        if not machine.nics:
            raise RuntimeError('You must have a nic to autoinstall')
        n = machine.nics[0]
        extra = 'ro noresume'
        extra += (' ip=%s::%s:%s:%s:eth0:off'
                  % (n.ip, config.dhcp.gateway, config.dhcp.netmask, machine.name))
        extra += ' %s' % installer_options
        root = '/dev/hdb1'
    codepath = None

    memory = max(memory, 512)
elif cdrom is not None:
    disk.append('phy:/dev/xenvg/image_' + cdrom.cdrom_id + ',hdc:cdrom,r')
    boot = 'd'
    codepath = 'hvm'

if codepath == 'hvm':
    ioemu = "ioemu:"
    viftype = "type=ioemu, "
    kernel = '/usr/lib/xen/boot/hvmloader'
    builder = 'hvm'
    vnc = 1
    device_model = '/usr/sbin/qemu-dm-invirt'
    serial = "pty"
elif codepath == 'paravm':
    bootloader = '/usr/bin/pygrub'


for n in machine.nics:
    check(re.match('^[0-9a-fA-F:]+$', n.mac_addr) and re.match('^[0-9.]*$', n.ip))
    d = ('%smac=%s, ip=%s, script=vif-invirtroute netdev=%s'
         % (viftype, n.mac_addr, n.ip, config.xen.iface))
    vif.append(d)

for d in machine.disks:
    check(re.match('^[A-Za-z0-9]+$', d.guest_device_name))
    device = '/dev/xenvg/' + prefix + machine.name + '_' + d.guest_device_name
    dspec = 'phy:%s,%s%s,w' % (device, diskioemu, d.guest_device_name)
    disk.append(dspec)

usbdevice = 'tablet'

on_poweroff = 'destroy'
on_reboot = 'restart'
on_crash = 'destroy'
if machine.autorestart:
    on_crash = 'restart'