#!/usr/bin/env python

import sys
import os.path
from subprocess import call, PIPE, Popen
from invirt.config import structs as config

def check(b):
    if not b:
        exit(1)

vg = "xenvg"
prefix = "d_"

subcommand = sys.argv[1]

def ensureoff(machine):
    # Make sure the machine is off, but we don't care about errors if it is already off.
    rv = call(["/usr/sbin/xm", "destroy", prefix + machine],
              stderr=PIPE)

if subcommand == "lvcreate-all":
    from invirt import database
    import re
    database.connect()
    for d in Disk.select():
        check(re.match('^[A-Za-z0-9]+$', d.guest_device_name))
        machine = Machine.get(d.machine_id)
        check(re.match('^[A-Za-z0-9][A-Za-z0-9._-]*$', machine.name))
        lvname = prefix + machine.name + "_" + d.guest_device_name
        if not os.path.exists("/dev/%s/%s" % (vg, lvname)):
            # LV doesn't exist
            print >>sys.stderr, "Creating LV %s..." % (lvname,)
            rv = call(["/sbin/lvcreate", "-L", str(d.size) + "M", "-n", lvname, vg])
            if rv != 0:
                print >>sys.stderr, "Error creating LV %s\n" %(lvname,)
                sys.exit(1)
else:
    machine = sys.argv[2]
    disk = sys.argv[3]
    lvname = prefix + machine + "_" + disk
    lvpath = "/dev/" + vg + "/" + lvname
if subcommand == "lvremove":
    def error():
        print >>sys.stderr, "Error removing LV %s\n" % lvname
        sys.exit(1)
    rv = call(["/sbin/lvchange", "-a", "n", lvpath])
    if rv != 0:
        error()
    rv = call(["/sbin/lvchange", "-a", "ey", lvpath])
    if rv != 0:
        error()
    rv = call(["/sbin/lvremove", "--force", lvpath])
    if rv != 0:
        error()
    ensureoff(machine)
elif subcommand == "lvresize":
    size = sys.argv[4]
    ensureoff(machine)
    p = Popen(["/sbin/lvresize", "-L", size + "M", lvpath],
              stdin=PIPE, stderr=PIPE)
    print >> p.stdin, 'y'
    err = p.stderr.read()
    if p.wait() != 0 and 'matches existing size' not in err:
        print >> sys.stderr, "Error resizing LV %s:\n" %(lvname,)
        print >> sys.stderr, err
        sys.exit(1)
    print >> sys.stderr, err
elif subcommand == "lvrename":
    newmachine = sys.argv[4]
    newlvname = prefix + newmachine + "_" + disk
    ensureoff(machine)
    ensureoff(newmachine)    
    rv = call(["/sbin/lvrename", vg, lvname, newlvname])
    if rv != 0:
        print >>sys.stderr, "Error renaming LV %s\n" %(lvname,)
        sys.exit(1)
elif subcommand == "lvcreate":
    size = sys.argv[4]
    rv = call(["/sbin/lvcreate", "-L", size + "M", "-n", lvname, vg])
    if rv != 0:
        print >>sys.stderr, "Error creating LV %s\n" %(lvname,)
        sys.exit(1)
    

