#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
Copyright 2013-2015, Markus Koschany <apo@gambaru.de>

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 package; if not, write to the Free Software Foundation, Inc., 51 Franklin
St, Fifth Floor, Boston, MA 02110-1301 USA
'''

from collections import defaultdict, OrderedDict

FNAME = "LICENSES"
STANDALONE_LICENSES = "standalone_licenses"
COPYRIGHT_FILE_MUSIC = "copyright_music"
COPYRIGHT_FILE_DATA = "copyright_data"
COPYRIGHT_FILE_MAPS = "copyright_maps"

GPL2 = "GNU General Public License 2.0"
GPL2PLUS = "GNU General Public License 2.0 or later"
GPL3PLUS = "GNU General Public License 3.0 or later"
PUBLIC_DOMAIN = "Public Domain"
EXPAT = "MIT/X11 license (GPL compatible)"
MIT = "MIT License"
CCBYSA3 = "Creative Commons Attribution-Share"
CCBY3 = "Creative Commons Attribution 3.0 Unported"
licenses = (GPL2, GPL2PLUS, GPL3PLUS, PUBLIC_DOMAIN, EXPAT, MIT, CCBYSA3,
            CCBY3)


def header():
    head = (
        "Format: http://www.debian.org/doc/packaging-manuals/"
        "copyright-format/1.0/\n"
        "Upstream-Name: UFO Alien Invasion\n"
        "Source: http://sourceforge.net/projects/ufoai/\n"
        "Comment:\n"
        " Please refer to the ufoai_copyright.py script in the ufoai\n"
        " source package for how a raw version of this copyright file\n"
        " is generated. All data was split into the three separate\n"
        " source packages ufoai-data, ufoai-maps and ufoai-music due\n"
        " to practical (size) and functional reasons.\n"
        "\n\n"
        "Files: *\n"
        "Copyright: 2002-2015, The UFO:AI Team\n"
        "License: GPL-2+\n"
        "\n\n"
        "Files: debian/*\n"
        "Copyright: 2013-2015, Markus Koschany <apo@gambaru.de>\n"
        "License: GPL-2+\n"
        "\n\n")
    return head


def license_shortname(license_name_full):
    '''Return the copyright format 1.0 shortname of the license'''
    if license_name_full == GPL2:
        shortname = "GPL-2"
    elif license_name_full == GPL2PLUS:
        shortname = "GPL-2+"
    elif license_name_full == GPL3PLUS:
        shortname = "GPL-3+"
    elif license_name_full == PUBLIC_DOMAIN:
        shortname = "public-domain"
    elif license_name_full == EXPAT:
        shortname = "Expat"
    elif license_name_full == MIT:
        shortname = "Expat"
    elif license_name_full == CCBYSA3:
        shortname = "CC-BY-SA-3.0"
    elif license_name_full == CCBY3:
        shortname = "CC-BY-3.0"
    return shortname


def paragraph(dict1, dict2):
    '''Print a copyright format 1.0 license paragraph
    dict1 - dictionary with license as key and files as values
    dict2 - dictionary with license as key and authors as unique values
    '''
    # Sort dictionary with files by its license key to get reproducible results
    dict1_sorted = OrderedDict(sorted(dict1.items(), key=lambda t: t[0]))
    # Print the whole license paragraph for all identically licensed files
    for license, v in dict1_sorted.items():
        print("Files:", file=cfile)
        for line in v:
            print(" {}".format(line.rstrip()), file=cfile)
        print("Copyright:", file=cfile)
        v = dict2[license]
        sname = license_shortname(license)
        for line in v:
            print("{}".format(line.rstrip()), file=cfile)
        print("License: {}\n".format(sname), file=cfile)


with open(FNAME, encoding="utf-8") as f:
    music_files = defaultdict(list)
    music_authors = defaultdict(set)
    data_files = defaultdict(list)
    data_authors = defaultdict(set)
    maps_files = defaultdict(list)
    maps_authors = defaultdict(set)
    # Loop over the file object
    for line in f:
        # Split every line by the | delimiter
        a_list = line.split("|")
        try:
            for license in licenses:
                if license in a_list[1]:
                    if license == GPL2 and GPL2PLUS in a_list[1]:
                        continue
                    else:
                        # Store information for music, data and maps separately
                        if a_list[0].startswith((
                                "base/music",
                                "base/sound")):
                            music_files[license].append(a_list[0])
                            music_authors[license].add(a_list[2])
                        elif a_list[0].startswith((
                                "base/materials",
                                "base/models",
                                "base/pics",
                                "base/shaders")):
                            data_files[license].append(a_list[0])
                            data_authors[license].add(a_list[2])
                        elif a_list[0].startswith((
                                "base/maps",
                                "base/textures")):
                            maps_files[license].append(a_list[0])
                            maps_authors[license].add(a_list[2])
        except (KeyError, IndexError):
            pass

# Write the converted output into three different copyright files
with open(STANDALONE_LICENSES, encoding="utf-8") as full_license_text:
    with open(COPYRIGHT_FILE_MUSIC, mode="w", encoding="utf-8") as cfile:
        cfile.write(header())
        paragraph(music_files, music_authors)
        cfile.write(full_license_text.read())

    with open(COPYRIGHT_FILE_DATA, mode="w", encoding="utf-8") as cfile:
        cfile.write(header())
        paragraph(data_files, data_authors)
        cfile.write(full_license_text.read())

    with open(COPYRIGHT_FILE_MAPS, mode="w", encoding="utf-8") as cfile:
        cfile.write(header())
        paragraph(maps_files, maps_authors)
        cfile.write(full_license_text.read())
