#!/usr/bin/env python
# Copyright 2011 Red Hat Inc.
# Author: Kushal Das <kdas@redhat.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.

import sys
import urllib2
import json
import os
from optparse import OptionParser

class DarkError:
    CONFIG_ERROR = 5
    NETWORK_ERROR = 2
    OPTION_ERROR = 4
    NODATA_ERROR = 1


def geturls():
    """
    Read the config file and get the URL(s)
    """
    if os.path.isfile('./darkclient.conf'):
        path = './darkclient.conf'
    elif os.path.isfile('/etc/darkclient.conf'):
        path = '/etc/darkclient.conf'
    else:
        return
    data = None
    with open(path) as fileobj:
        data = fileobj.readlines()
    return [line.strip('\n') for line in data]

def callback(option, opt_str, value, parser):
    "Callback method"
    args = []
    for arg in parser.rargs:
        if arg[0] != "-":
            args.append(arg)
        else:
            del parser.rargs[:len(args)]
            break
    if getattr(parser.values, option.dest):
        args.extend(getattr(parser.values, option.dest))
    setattr(parser.values, option.dest, args)

def readurl(url):
    """
    Reads the URL and returns decoded json objects
    """
    ret = 0
    data = None
    try:
        fileobj = urllib2.urlopen(url)
        textdata = fileobj.read()
        fileobj.close()
        data = json.loads(textdata)
    except urllib2.URLError, error:
        print error
        ret = DarkError.NETWORK_ERROR
    return data, ret

def dark_find_ids(url, ids):
    """
    Find the ids given and print the result
    """
    turl = url + "/buildids/"
    for gid in ids:
        turl = turl + gid + ','

    turl = turl[:-1]

    data, ret = readurl(turl)
    if ret != 0:
        return ret

    if len(data) == 0:
        return DarkError.NODATA_ERROR

    for text in data:
        print text['buildid'], text['rpm'], text['elf']
    return 0

def dark_find_rpm(url, name):
    """
    Find the ids given and print the result
    """
    turl = url + "/rpm2buildids/%s" % name

    data, ret = readurl(turl)

    if ret != 0:
        return ret
    if not data:
        return DarkError.NODATA_ERROR

    for text in data:
        print text['buildid'], text['rpm'], text['elf']
    return 0

def dark_find_package(url, name):
    """
    Find the download URL for the package
    """
    turl = url + "/package/%s" % name

    data, ret = readurl(turl)

    if ret != 0:
        return ret
    if not data:
        return DarkError.NODATA_ERROR


    if 'url' in data:
        print data['url']
        return 0
    else:
        return DarkError.NODATA_ERROR



def main(args):
    """
    Main function
    """
    parser = OptionParser()
    parser.add_option('-i', '--ids', help="GNU build-id(s)", dest='ids', \
                      action = 'callback', callback=callback)
    parser.add_option("-r", "--rpm", dest="rpm", \
                      help = "Name of the rpm file to find build-id(s)")

    parser.add_option('-p', '--package', help="Download URL for package", \
                        dest='package')

    (options, args) = parser.parse_args(args[1:])
    url = geturls()
    if url != None:
        url = url[0]
    else:
        sys.exit(DarkError.CONFIG_ERROR)
    code = DarkError.OPTION_ERROR
    if options.ids:
        code = dark_find_ids(url, options.ids)
    elif options.rpm:
        code = dark_find_rpm(url, options.rpm)
    elif options.package:
        code = dark_find_package(url, options.package)
    else:
        sys.stderr.write("Please provide rpm or id details\n")

    return code



if __name__ == '__main__':
    code = main(sys.argv)
    sys.exit(code)
