#!/usr/bin/python3
#
# Copyright 2016 Red Hat, Inc.
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#

from __future__ import absolute_import

import argparse
import logging
import sys

log = logging.getLogger("vercmp")


def main(args):
    args = parse_args()
    if args.verbose:
        level = logging.DEBUG
    else:
        level = logging.INFO

    logging.basicConfig(level=level, format="%(name)s: %(message)s")
    return compare_versions(args.actual_version, args.required_version)


def compare_versions(actual_version, required_version):
    actual_version = [int(n) for n in actual_version.split('.')]
    required_version = [int(n) for n in required_version.split('.')]

    padding = len(actual_version) - len(required_version)
    if padding > 0:
        required_version += [0] * padding

    if actual_version < required_version:
        log.debug("%s < %s", actual_version, required_version)
        return 0
    elif actual_version == required_version:
        log.debug("%s == %s", actual_version, required_version)
        return 1
    else:
        log.debug("%s > %s", actual_version, required_version)
        return 2


def parse_args():
    parser = argparse.ArgumentParser(
        description='Compare actual version to required version.\n'
                    'This utility supports only version numbers separated by '
                    'dots.', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('actual_version')
    parser.add_argument('required_version')
    parser.add_argument('-v', '--verbose', help='increase output verbosity',
                        action='store_true', default=False)
    return parser.parse_args()

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
