#!/usr/local/cpython-3.6/bin/python3

# pylint: disable=wrong-import-position
# pylama: ignore=E402

"""
Read a list of filenames, null-terminated.

Each file will be in a subdirectory.
Keep the file from the subdirectory that is biggest.
"""

import os
import sys
import shutil
import functools
import collections

sys.path.insert(0, '/usr/local/lib')

import readline0


@functools.total_ordering
class File:
    # pylint: disable=too-few-public-methods

    """Hold one file."""

    def __init__(self, relative_path):
        """Initializer."""
        self.relative_path = relative_path
        self.length = os.path.getsize(relative_path)
        self.dirname = os.path.dirname(self.relative_path)
        self.filename = os.path.basename(self.relative_path)

    def __str__(self):
        """Convert this File to a string representation."""
        return '{} {}'.format(self.dirname, self.filename)

    __repr__ = __str__

    def __lt__(self, other):
        """Return True iff self < other."""
        if self.length < other.length:
            return True
        return False

    def __eq__(self, other):
        """Return True iff self == other."""
        if self.length == other.length:
            return True
        return False


def usage(exit_code):
    """Output a usage message."""
    if exit_code == 0:
        write = sys.stdout.write
    else:
        write = sys.stderr.write

    write('Usage: {} --output-dir /output/directory\n'.format(sys.argv[0]))
    write('\n')
    write('Input is null-separated relative paths on stdin\n')
    write('\n')
    write('EG, you might have 3 directories, all with more-or-less the same file basename\'s in them.\n')
    write('{} will keep the biggest basename file from each directory inm the output directory\n'.format(sys.argv[0]))

    sys.exit(exit_code)


def main():
    """Main function."""
    output_dir = None

    while sys.argv[1:]:
        if sys.argv[1] in ('-o', '--output-dir'):
            output_dir = sys.argv[2].encode('UTF-8')
            del sys.argv[1]
        elif sys.argv[1] in ('-h', '--help'):
            usage(0)
        else:
            sys.stderr.write('{}: Unrecognized option: {}\n'.format(sys.argv[0], sys.argv[1]))
            usage(1)
        del sys.argv[1]

    if output_dir is None:
        sys.stderr.write('{}: --output-dir is a required option\n'.format(sys.argv[0]))
        usage(1)

    os.makedirs(output_dir)

    files = collections.defaultdict(list)
    for filename in readline0.readline0():
        one_file = File(filename)
        files[one_file.filename].append(one_file)
    for filename in files:
        files[filename].sort()
    for filename in files:
        this_file = files[filename][-1]
        print('Copying {} to {}'.format(this_file.relative_path, output_dir))
        shutil.copy(this_file.relative_path, output_dir)

main()