#!/usr/bin/python
from MgaRepo import Error, config
from MgaRepo.command import *
from MgaRepo.util import execcmd, get_helper
import sys


HELP = """\
Usage: 
    Take maintainership of one package :
       mgarepo maintdb set [package] [login]

    Remove yourself from maintainer of a package :
       mgarepo maintdb set [package] nobody

    See who is maintainer of a package :
       mgarepo maintdb get [package]

    See the list of all packages with their maintainer :
       mgarepo maintdb get

"""

def parse_options():
    parser = OptionParser(help=HELP)
    opts, args = parser.parse_args()
    if len(args):
        opts.maintdb_args = args
    else:
        raise Error("you need to provide arguments, see them with --help")
    return opts

def maintdb(maintdb_args):
    host = config.get("maintdb", "host", "maintdb.mageia.org")
    if (maintdb_args[0] == 'get' and len(maintdb_args)>=2):
        url = config.get("maintdb", "url", "https://maintdb.mageia.org/")
        import urllib.request
        try:
            page=urllib.request.urlopen(url + maintdb_args[1])
            rep = page.read().decode('utf8')
        except urllib.error.HTTPError as e:
            if e.code == 404 :
                rep = "There is no package named {}".format(maintdb_args[1])
            else:
                rep = e.reason
        except Exception as e:
            rep = "Error trying to query the database: {}. Do you have an active Internet connection?".format(e.reason)
        print(rep)
    else:
        maintdb_helper = get_helper("maintdb")
        cmd_args = ' '.join(maintdb_args)
        command = "ssh %s %s %s" % (host, maintdb_helper, cmd_args)
        execcmd(command, show=True)
    sys.exit(0)

def main():
    do_command(parse_options, maintdb)

# vim:et:ts=4:sw=4
