#!/usr/bin/python
#
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys
from optparse import Option, OptionParser
from spacewalk.common.rhnConfig import CFG, initCFG
from spacewalk.server import rhnSQL
from spacewalk.server.taskomatic import add_to_repodata_queue


def __listChannels():
    sql = """
        select c1.label, c2.label parent_channel
        from rhnChannel c1 left outer join rhnChannel c2 on c1.parent_channel = c2.id
        where c1.checksum_type_id is not null
        order by c2.label desc, c1.label asc
    """
    h = rhnSQL.prepare(sql)
    h.execute()
    labels = {}
    parents = {}
    while 1:
        row = h.fetchone_dict()
        if not row:
            break
        parent_channel = row['parent_channel']
        labels[row['label']] = parent_channel
        if not parent_channel:
            parents[row['label']] = []

        if parent_channel:
            parents[parent_channel].append(row['label'])

    return labels, parents


if __name__ == '__main__':
    options_table = [
        Option("-l", "--list", action="store_true",
               help="List defined channels and exit."),
        Option("-a", "--all", action="store_true",
               help="Schedule repodata creation for all channels."),
        Option("-c", "--channel", action="append",
               help="Schedule repodata creation for this channel (can be present multiple times)."),
    ]

    parser = OptionParser(option_list=options_table)
    (options, args) = parser.parse_args()

    if args:
        for arg in args:
            sys.stderr.write("Not a valid option ('%s'). Try --help\n" % arg)
    if not (options.list or options.all or options.channel):
        sys.stderr.write("No option specified. Try --help\n")
    if (options.all and options.channel):
        sys.stderr.write("You need to specify either --all or --channel.\n")
        sys.exit(1)

    initCFG('server')
    rhnSQL.initDB()
    rhnSQL.clear_log_id()
    rhnSQL.set_log_auth_login('SETUP')

    dict_label, dict_parents = __listChannels()
    if options.list:
        keys = dict_parents.keys()
        keys.sort()
        for c in keys:
            print c
            for sub in dict_parents[c]:
                print "\t+- " + sub
        sys.exit(0)

    if options.channel:
        valid_labels = True
        for channel in options.channel:
            if not channel in dict_label.keys():
                sys.stderr.write("Invalid channel label specified: '%s'\n" % channel)
                valid_labels = False
        if not valid_labels:
            sys.exit(1)

        for channel in options.channel:
            print "Scheduling repodata creation for '%s'" % channel
            add_to_repodata_queue(channel, 'regenerate-repodata', '')
            rhnSQL.commit()
        sys.exit(0)

    if options.all:
        for channel in dict_label.keys():
            print "Scheduling repodata creation for '%s'" % channel
            add_to_repodata_queue(channel, 'regenerate-repodata', '')
            rhnSQL.commit()
        sys.exit(0)
