#!/opt/vertica/oss/python/bin/python
import readline
import subprocess
import sys
import atexit
from optparse import OptionParser
import os.path

from vertica.tools import CatalogEditor

class CatalogEditorShell:
    def __init__(self, ce):
        self.cmds = ["list","listdetails","dependents","dependentdetails","antecedents","show","table","get","set","create","drop","commit","rollback","chkpts","txnlogs","checkpoint","summary","versionsjson","versions","design","lge","roses","nodedeps","dc","dcd","dclist","tofile","setdelim","setparameter","showparameter","clearparameter","exit","quit","help"]

        self.typecmds = ["list ","listdetails ","table ","create "]
        self.thingcmds = ["dependents ","dependentdetails ","antecedents ","show ","get ","set ","drop "]
        self.thingtypes = ["oid ","name ","singleton "]
        self.dccmds = ["dc ","dcd "]
        self.ce = ce
        self.ce.get_type_info()
        self.ce.get_dc_info()
        self.types = [x[0] for x in ce.types]
        self.dctables = ce.dctables
        self.objinfo = {}

    def completer(self, text, state):
        line = readline.get_line_buffer()
        if text == line:
            options = [c for c in self.cmds if c.startswith(text)]
            if state < len(options):
                return options[state]
            else:
                return None
        elif [c for c in self.typecmds if line.startswith(c)]:
            options = [t for t in self.types if t.startswith(text)]
            if state < len(options):
                return options[state]
            else:
                return None
        elif [c for c in self.thingcmds if line.startswith(c)]:
            part = line.split()
            if part[-1] == text:
                part = part[0:-1]
            if len(part) == 1:
                options = [t for t in self.thingtypes if t.startswith(text)]
                if state < len(options):
                    return options[state]
                else:
                    return None
            elif len(part) == 2:
                if part[1] != "oid":
                    options = [t for t in self.types if t.startswith(text)]
                    if state < len(options):
                        return options[state]
                    else:
                        return None
            elif len(part) == 3:
                if part[1] == "name" and part[2] in self.types:
                    options = [t for t in self.get_obj_info(part[2]) if t.startswith(text)]
                    if state < len(options):
                        return options[state]
                    else:
                        return None
        elif [c for c in self.dccmds if line.startswith(c)]:
            options = [t for t in self.dctables if t.startswith(text)]
            if state < len(options):
                return options[state]
            else:
                return None
        return None

    def get_obj_info(self,objtype):
        if not self.objinfo.get(objtype):
            str = self.ce.sendCmd("table %s name"%objtype).rstrip()
            if '\x02' in str:
                elems = str.split('\x02')
            else:
                elems = str.split()
            elems = elems[1:]    # remove header
            if elems and elems[-1] == '':
                elems = elems[:-1]
            self.objinfo[objtype] = elems
        return self.objinfo[objtype]

    def interactive_shell(self):
        readline.parse_and_bind("tab: complete");
        readline.set_completer(self.completer)
        cmd = ""
        while cmd != "exit":
            cmd = raw_input("> ")
            print self.ce.sendCmd(cmd)

def build_conf(cfname, ce):
    def remove_trailing_bits(comp, path):
        first, second = os.path.split(path)
        if comp in second:
            return first
        else:
            return path
    ce.sendCmd("setdelim , \\n")
    dbname = ce.sendCmd("get singleton Database name").rstrip()
    nodes = ce.sendCmd("table Node oid name address catalogPath").rstrip().split("\n")
    header = nodes[0]
    nodes = nodes[1:]
    ns = [n.split(",") for n in nodes]
    for n in ns:
        # prune off node name from catalog path
        n[3] = remove_trailing_bits(dbname,
                                    remove_trailing_bits(n[1],
                                                         remove_trailing_bits("Catalog",n[3])))
        # find storage location
        slocoid = ce.sendCmd("dependents oid "+n[0]).split()[0]
        spath = ce.sendCmd("get oid %s path" % slocoid)
        spath = remove_trailing_bits(dbname,remove_trailing_bits(n[1], spath))
        n.append(spath)

    #print dbname
    #print ns

    ctext = """[Configuration]
show_hostnames = False

[Cluster]
hosts = %s
spread_hosts = 

[Database:%s]
host = %s
restartpolicy = never
port = 5433
path = %s
nodes = %s
 
[Nodes]
""" % (",".join([n[2] for n in ns]),dbname,ns[0][2],ns[0][3],",".join([n[1] for n in ns]))
    for n in ns:
        ctext = ctext + "%s = %s,%s,%s\n" % (n[1],n[2],n[3],n[4])

    if cfname != 'stdout':
        cfile = open(cfname,'w')
        cfile.write(ctext)
        cfile.close()
    else:
        print ctext

def get_cat_dump(cfdir, ce, exclude = {}):
    ce.get_type_info()
    for t in ce.types:
        print 'Getting', t
        ce.sendCmd("table "+t+" *","%s/%s" % (cfdir,t))

def get_dc_tables(cfdir, ce, exclude={}):
    ce.get_dc_info()
    for t in ce.dctables:
        print 'Getting', t
        ce.sendCmd("dcd "+t, "%s/%s" % (cfdir,t))

def main():
    parser = OptionParser()
    parser.add_option("-b","--binary",dest="binary",
                      help="Location of vertica binary",default="/opt/vertica/bin/vertica")
    parser.add_option("-D","--catalogpath",dest="catalogpath",
                      help="Catalog directory",default=False)
    parser.add_option("-z","--zippy",action="store_true",dest="zippy",
                      help="Read only config info from catalog",default=False)
    parser.add_option("-c","--conf",dest="conf",
                      help="Generate admintools.conf to given filename",default=False)
    parser.add_option("-O","--objects",dest="dumpobjects",
                      help="Dump catalog objects to directory",default=False)
    parser.add_option("-d","--dc",dest="dumpdc",
                      help="Dump DC tables to directory",default=False)
    (options, args) = parser.parse_args()
    if not options.catalogpath:
        print "Usage: "+sys.argv[0]+" -D <catalogdir>"
    else:
        ce = CatalogEditor.CatalogEditor(catalogpath=options.catalogpath,verticabin = options.binary, zippy=(options.zippy or options.conf))
        if options.conf:
            build_conf(options.conf, ce)
        elif options.dumpobjects:
            get_cat_dump(options.dumpobjects, ce)
        elif options.dumpdc:
            get_dc_tables(options.dumpdc, ce)
        else:
            print ce.header_text
            csh = CatalogEditorShell(ce)
            csh.interactive_shell()

if __name__ == "__main__":
    main()

