#!/usr/bin/python
import os,sys
from argparse import ArgumentParser
libdir="/usr/local/lib/vws"
drivename="drive0.qcow2"
args = ArgumentParser()

args.add_argument("--no-usb",help="Disable USB controller",action='store_const', const = False, default=True, dest="usb")
args.add_argument("--size",help="Size of primary disk images",dest="size",default="20G");
args.add_argument("--arch",help="Emulated architecture",dest="arch",default='x86_64');
args.add_argument("--no-sound",help="Disable sound card",action='store_const',const = False, default=True, dest="sound")
args.add_argument("--net",help="Network - 'user' or bridge name",dest='net',default="user")
args.add_argument("--mem",help="Size of memory",dest="mem",default="1024M")
args.add_argument("--diskif",help="Disk interface",dest="diskif",default="virtio")
args.add_argument('name',type=str,help='name of machine to create')
args.add_argument('--shared',help='Create shared VM instead of private one',action='store_const',const= True,dest='shared',default=False)
args.add_Argumnen('--image',help='Existing disk image to import',dest=image,default=None))
parsed_args = args.parse_args(sys.argv[1:])

options={'qemubinary':'qemu-system-x86_64',
"accel":"-enable-kvm",
"memory":"1024M",
"drive":"-drive media=disk,index=0,if={interface},file={image}",
"cdrom":"-drive media=cdrom,index=2,if=ide",
"sound":"-soundhw hda",
"usb":"-usb"}


macaddr=":".join(map(lambda x: "%02x"%random.randrange(0,256),range(0,5)))

if parsed_args.net != 'user':
    options["net"]="-net nic,macaddr=%s -net bridge,br=%s"%(macaddr,parsed_args.net),
else:
    options["net"]="-net nic,macaddr=%s -net user"%(macaddr,))

optons["qemubinary"] = 'qemu-system-'+parset_args.arch

if not parsed_args.arch in ('i386','x86_64'):
    print >>sys.stderr,"KVM acceleration disabled due to target architecture"
    options.accel = ''
elif not os.access("/dev/kvm",os.W_OK):
    print >>sys.stderr,"KVM acceleration disabled due to unavailability on the host system"
    options.accel = ''

if not parsed_args.usb:
    options["usb"]=''

if not parsed_args.sound:
    options["sound"]=''

options["memory"]=parsed_args.mem


#  Creating directory for VM

driveopts={"interface":parsed_args.diskif,"image":drivename}
if parsed_args.image:
    # Copying image file
    print >>sys.stderr,"Copying %s to %s"%(parsed_args.image,machinedir+"/"+drivename)

    chdir(machinedir)
else:
    print >>sys.stderr,"Creating new image file"
    os.chdir(machinedir)
    os.system("qemu-img create -f qcow2 %s %s"%(drivename,parsed_args.size))
options["drive"]=options["drive"].format(driveopts) 
with open(libdir+"/start.template","r") as f:
    template=f.read()
with open("start","w") as script:
    print script,template.format(options),

os.chmod(start,0755)

# If installation media is specified vws start for new vm

