#!/usr/bin/env python3
#
# This script lists the packages (and their versions) in a PPA (optionally
# for a given series)
#
# Copyright (C) 2019 Canonical, Ltd
# Author: Mike Salvatore <mike.salvatore@canonical.com>
# License: GPLv3

import lpl_common
import argparse
import sys

def print_error_and_exit(parser, msg):
    print(msg + " \n")
    parser.print_help()
    sys.exit(1)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--release", help="List packages for this ubuntu series (if none specified, will list for all)",
                        action="store")
    parser.add_argument("ppa", metavar='PPA', help="List packages for this ubuntu series (i.e. \"ubuntu-security/ppa\"",
                        action="store")

    args = parser.parse_args()
    return args

def get_records_from_ppa(opt):
    lp = lpl_common.connect()
    distribution = lp.distributions['ubuntu']
    ubuntu = lp.distributions['ubuntu']
    series = None
    if opt.release:
        series = ubuntu.getSeries(name_or_version=opt.release)
    archive, group, ppa = lpl_common.get_archive(opt.ppa, lp, False, distribution=distribution)
    return archive.getPublishedSources(status='Published', distro_series=series)


args = parse_args()
records = get_records_from_ppa(args)

for record in records:
    print('%s:%s [%s]' % (record.source_package_name, record.source_package_version, record.distro_series.name))
