#!/usr/bin/python

import os
import sys
import xml
from xml.dom.minidom import parseString
import subprocess

def get_output(cmd, ignoreerr = False, stdout = subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE):
    proc = subprocess.Popen(cmd,
                            shell=True,
                            stderr=stderr,
                            stdout=stdout,
                            stdin=stdin)
    output, err = proc.communicate()
    ret = proc.returncode
    if ret:
        errormsg = '`%s\'returned %i:\n %s\n' % (cmd, ret, err)
        if not ignoreerr:
            print "Output:\n%s" % output
            print "Errors:\n%s" % err
            raise ValueError(errormsg)
    return (output, ret)

# Get clustername
if len(sys.argv) < 2 or not sys.argv[1]:
    print "Usage: %s CLUSTERNAME [--drop_unavail]" % sys.argv[0]
    sys.exit(1)

drop = False
try:
    if sys.argv[2] == "--drop_unavail":
        drop = True
except:
    pass

listd = "/etc/vstorage/clusters/%s" % sys.argv[1]
listf = "%s/bs.list" % listd

if not os.path.exists(listd):
    print "Cluster %s does not exist: %s absent" % (sys.argv[1], listd)
    sys.exit(1)

if not os.path.exists(listf):
    open(listf, 'w').close()

xml_out = get_output("vstorage -c %s stat -X" % sys.argv[1])[0]

vstat = parseString(xml_out)

ipps = []
status = []

try:
    for mds in vstat.getElementsByTagName("mds_list"):
        for m in mds.getElementsByTagName("mds"):
            for z in m.getElementsByTagName("status"):
                status.append(z.childNodes[0].data)
            for p in m.getElementsByTagName("host_info"):
                for d in p.getElementsByTagName("host"):
                    ipps.append(d.childNodes[0].data)
except:
    print "Failed to parse xml"
    sys.exit(1)


if not ipps:
    print "No MDS ips available"
    sys.exit(0)

cached_ipps = []

# Get already cached IPs
with open(listf, "r") as f:
    cached_ipps = [ l.rstrip('\n') for l in f.readlines() if l and not l.startswith('#') ]
    f.close()

new_ips = False
todrop = False

for i in range(0, len(ipps)):
    if not ipps[i] in cached_ipps and status[i] == "avail":
        new_ips = True
        cached_ipps.append(ipps[i])
    if ipps[i] in cached_ipps and status[i] == "unavail" and drop:
        todrop = True
        cached_ipps.remove(ipps[i])

if not new_ips:
    print "No new MDS ips found"
    if not todrop:
        sys.exit(0)

with open(listf, "w") as f:
    for ip in cached_ipps:
        f.write(ip + '\n')
    f.close
