#!/opt/sunpy3/bin/python3
#coding:utf-8
import os,sys
import getopt
import sunhpc.invoke
from xml.sax._exceptions import SAXParseException
class App(sunhpc.core.database.ApplicationSQL):

    def __init__(self, argv=None):
        sunhpc.core.database.ApplicationSQL.__init__(self)

        if not argv:
            argv = sys.argv

        self.args           = []
        self.caller_args    = argv[1:]
        self.usage_name     = 'Kickstart Generator'
        self.usage_version  = '1.0'
        self.usage_command  = os.path.basename(argv[0])
        self.sections       = []

        self.os         = os.uname()[0].lower()
        self.arch       = os.uname()[4]
        osGenerator     = getattr(sunhpc.core.xmlgen, 'Generator_%s' % self.os)
        self.generator  = osGenerator()
        self.generator.setArch(self.arch)
        self.generator.setOS(self.os)

        self.getopt     = sunhpc.core.utils.Struct()
        self.getopt.s   = [('h', 'help infomation'), ('a', 'architecture')]
        self.getopt.l   = [('arch=', 'architecture'),
                           ('section=', 'name'),
                           ('postonly', 'show post'),
                          ]
    def usage(self):
        argDict = {}
        for e in self.getopt.s:
            if type(e) == type(()):
                argDict['-%s' % e[0]] = e[1]
            else:
                argDict['-%s' % e] = ''

        for l in self.getopt.l:
            if type(l) == type(()):
                argDict['--%s' % l[0]] = l[1]
            else:
                argDict['--%s' % l] = ''

        if not argDict: return
        maxlen = max(map(len, argDict.keys()))
        print ('\nUsage: %s [options] command infomations' % self.usage_command)
        for k in argDict:
            keys = k.ljust(maxlen)
            vals = argDict[k]
            print ('  %s\t%s' % (keys, vals))
        print ('If you have any questions, please contact info@sunhpc.com')

    def parseArg(self, c):
        if c[0] in ('-h', '--help'):
            self.usage()
            sys.exit(-1)
        elif c[0] in ('-a', '--arch'):
            self.generator.setArch(c[1])
        elif c[0] == '--section':
            self.sections += c[1].split()
        elif c[0] == '--postonly':
            self.sections.append('post')
        else:
            return 0
        return 1

    def parseArgs(self):
        self.parseCommandLine()

    def parseCommandLine(self):
        # 解析短参数形式
        short = ''
        for e in self.getopt.s:
            if type(e) == type(()):
                # 取参数左值
                short = short + e[0]
            else:
                short = short + e

        # 解析长参数形式
        long = []
        for e in self.getopt.l:
            if type(e) == type(()):
                # 取参数左值
                long.append(e[0])
            else:
                long.append(e)
        try:
            opts, args = getopt.getopt(self.caller_args, short, long)
        except getopt.GetoptError as msg:
            sys.stderr.write('error - %s\n' % msg)
            self.usage()
            sys.exit(1)

        for c in opts:
            self.parseArg(c)

    def run(self):

        if self.args:
            fe = open(self.args[0], 'r')
        else:
            fe = sys.stdin

        self.generator.parse(fe.read())
        print ('#')
        print ('# %s version %s' % (self.usage_name, self.usage_version))
        print ('#')

        sections = self.sections
        if not sections:
            sections = ['order', 'debug', 'main', 'packages', 'pre', 'post']

        plist = []
        for s in sections:
            plist += self.generator.generate(s)

        for line in plist:
            print (line.rstrip())

if __name__ == "__main__":
    app = App(sys.argv)
    app.parseArgs()
    try:
        app.run()
    except sunhpc.core.exceptions.KickstartError as msg:
        sys.stderr.write("kgen error - %s\n" % msg)
        sys.exit(-1)

    except SAXParseException as msg:
        sys.stderr.write("kgen XML parse exception: %s\n" % msg)
        sys.exit(-1)
    



















