#!/opt/alt/python27/bin/python2.7
# -*- coding: utf-8 -*-

import sys
import os
import getopt
import simplejson

class ParseText(object):
    def __init__(self, source):
        if not os.path.isfile(source):
            print "ERROR: invalid source (%s)" % (source,)
            sys.exit(2)
        self.dataset = []
        source_handle = open(source,'r')
        for line in source_handle:
            if '=' not in line:
                continue
            (extension_name, extension_description) = line.strip().split('=')
            self.dataset.append(
                {'title':extension_name,
                'description':extension_description})
        source_handle.close()
    def print_perl(self):
        print "[\n"
        for i in self.dataset:
            print "\t{\n\t\ttitle => \"%s\",\n\t\tdescription => \"%s\"\n\t}," % ( i['title'], i['description'] )
        print "]"
        
    def print_json(self):
        print simplejson.dumps(self.dataset)
        
    def print_text(self):
        for i in self.dataset:
            print "%s=%s" % ( i['title'], i['description'] )
            
def usage():
    print ''
    print 'Usage: ' + sys.argv[0] + ' [OPTIONS]'
    print 'Options:'
    print ''
    print ' -p | --perl   : return perl-compartible structure'
    print ' -j | --json   : return json structure'
    print ' -s | --source : specify source file (by default /etc/cl.selector/phpextdesc.txt'
    print ' -h | --help   : print this message'
    print 'By default data is outputted as colon separated text'
    print ''
    
def main():
    
    config = {}
    config['perl'] = False
    config['json'] = False
    config['source'] = '/etc/cl.selector/phpextdesc.txt'
    
    try:
        opts, args = getopt.getopt( sys.argv[1:], 'hpjs:', [ 'help', 'perl', 'json', 'source=' ] )
    except getopt.GetoptError:
        usage()
        sys.exit(1)
        
    for o, a in opts:
        if o in [ '-h', '--help' ]:
            usage()
        elif o in [ '-s', '--source' ]:
            config['xmlsource'] = a
        elif o in [ '-p', '--perl' ]:
            config['perl'] = True
        elif o in [ '-j', '--json' ]:
            config['json'] = True
            
    xml_doc = ParseText(config['source'])
    if config['perl'] and not config['json']:
        xml_doc.print_perl()
    elif config['json']:
        xml_doc.print_json()
    else:
        xml_doc.print_text()


if __name__ == '__main__':
    main()
