#!/usr/bin/env python3
#  Copyright  2020 Alexis Lopez Zubieta
#
#  Permission is hereby granted, free of charge, to any person obtaining a
#  copy of this software and associated documentation files (the "Software"),
#  to deal in the Software without restriction, including without limitation the
#  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
#  sell copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
import argparse
import logging
import os

from AppImageBuilder.inspector.inspector import Inspector


def configure_logging(args):
    numeric_level = getattr(logging, args.loglevel.upper())
    if not isinstance(numeric_level, int):
        logging.error('Invalid log level: %s' % args.loglevel)
    logging.basicConfig(level=numeric_level)


def __main__():
    parser = argparse.ArgumentParser(description='AppImage/AppDir analysis tool')
    parser.add_argument('target', help='AppImage or AppDir to be inspected')
    parser.add_argument('--log', dest='loglevel', default="INFO", help='logging level (default: INFO)')
    parser.add_argument('--print-needed', dest='do_print_needed', action='store_true',
                        help='Print bundle needed libraries')
    parser.add_argument('--print-runtime-needed', dest='do_print_runtime_needed', action='store_true',
                        help='Print bundle needed libraries for the current system')

    parser.add_argument('--print-dependants', dest='do_print_dependants',
                        help='Print bundle libraries that depends on')

    args = parser.parse_args()
    configure_logging(args)

    inspector = Inspector(args.target)
    if args.do_print_needed:
        needed = inspector.get_bundle_needed_libs()
        for lib in sorted(needed):
            print("%s" % lib)

    if args.do_print_runtime_needed:
        dependants = inspector.get_bundle_runtime_needed_libs()
        dependants = [os.path.basename(lib) for lib in dependants]
        for lib in sorted(dependants):
            print("%s" % lib)

    if args.do_print_dependants:
        dependants = inspector.get_dependants_of(args.do_print_dependants)
        for lib in sorted(dependants):
            print("%s" % lib)


if __name__ == '__main__':
    __main__()
