#!/usr/bin/python
# Copyright (c) 2016 SUSE LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from pprint import pprint
import os, sys, re
import logging
import cmdln
from xml.etree import cElementTree as ET
from pprint import pformat

ZYPP_REPOS_D = 'etc/zypp/repos.d/'
CONTROL_XML = 'etc/YaST2/control.xml'

class JeOSTool(cmdln.Cmdln):
    def __init__(self, *args, **kwargs):
        cmdln.Cmdln.__init__(self, args, kwargs)
        self.dryrun = False

    def get_optparser(self):
        parser = cmdln.CmdlnOptionParser(self)
        parser.add_option("--dry", action="store_true", help="dry run")
        parser.add_option("--debug", action="store_true", help="debug output")
        parser.add_option("--verbose", action="store_true", help="verbose")
        return parser

    def postoptparse(self):
        level = None
        if self.options.debug:
            level  = logging.DEBUG
        elif self.options.verbose:
            level = logging.INFO

        logging.basicConfig(level = level)

        self.logger = logging.getLogger(self.optparser.prog)

        if self.options.dry:
            self.dryrun = True

    @cmdln.option("-r", "--root", metavar="DIR", default='/',
                  help="root directory")
    def do_create_repos(self, subcmd, opts):
        """${cmd_name}: generate repos from control.xml

        ${cmd_usage}
        ${cmd_option_list}
        """

        ns = { 'yast2': 'http://www.suse.com/1.0/yast2ns',
            'config': 'http://www.suse.com/1.0/configns' }

        fh = open(os.path.join(opts.root, CONTROL_XML), 'r')
        root = ET.parse(fh).getroot()
        fh.close()
        for node in root.findall('.//yast2:extra_url', ns):
            settings = {
                    'alias' : None,
                    'autorefresh' : 0,
                    'baseurl' : None,
                    'enabled' : 0,
                    'keeppackages' : 0,
                    'name' : None,
                    'priority' : 99,
                    'prod_dir' : None,
                    'type' : 'NONE',
                    }
            for i in settings.keys():
                n = node.find('yast2:%s'%i, ns)
                if n is None:
                    continue
                t = n.get('{http://www.suse.com/1.0/configns}type', None)
                if t == 'boolean':
                    settings[i] = 1 if n.text == 'true' else 0
                else:
                    settings[i] = "%s"%n.text

            self.logger.debug(pformat(settings))

            repo = """[%(alias)s]
name=%(name)s
enabled=%(enabled)s
autorefresh=%(autorefresh)s
baseurl=%(baseurl)s
path=%(prod_dir)s
keeppackages=0
priority=%(priority)s
type=%(type)s
"""%settings
            fn = os.path.join(opts.root, ZYPP_REPOS_D, settings['alias']+'.repo')
            self.logger.info('creating %s'%fn)
            self.logger.debug(repo)
            if not self.dryrun:
                fh = open(fn, 'w')
                fh.write(repo)
                fh.close()

if __name__ == "__main__":
    app = JeOSTool()
    sys.exit( app.main() )

# vim: sw=4 et
