#!/usr/bin/env python3

from pathlib import Path
import sys


def main():
    print(
        """Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: LDraw Parts
Source: https://library.ldraw.org/updates?latest
Files-Excluded:
 mklist.exe
 mklist1_4.zip
 mklist1_6.zip
 mklist-c.zip
Comment: auto-generated by debian/gencopyright.py -- do not edit manually
"""
    )
    curdir = Path(".")
    authors = {"CC-BY-2.0 and CC-BY-4.0": set(), "CC-BY-2.0": set(), "CC-BY-4.0": set()}
    files = {
        "CC-BY-2.0 and CC-BY-4.0": list(),
        "CC-BY-2.0": list(),
        "CC-BY-4.0": list(),
    }
    for glob in [
        "./models/*.dat",
        "./p/*.dat",
        "./p/48/*.dat",
        "./parts/*.dat",
        "./parts/s/*.dat",
    ]:
        for p in curdir.glob(glob):
            if not p.is_file():
                continue
            author = None
            ccby = None
            with p.open() as f:
                for line in f:
                    if line.startswith("0 Author: "):
                        author = line.removeprefix("0 Author: ").removesuffix("\n")
                    if line.startswith("0 !LICENSE "):
                        match line:
                            case "0 !LICENSE Licensed under CC BY 2.0 and CC BY 4.0 : see CAreadme.txt\n":
                                ccby = "CC-BY-2.0 and CC-BY-4.0"
                            case "0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt\n":
                                ccby = "CC-BY-2.0"
                            case "0 !LICENSE Licensed under CC BY 4.0 : see CAreadme.txt\n":
                                ccby = "CC-BY-4.0"
                            case _:
                                raise Exception(f"unexpected license in {p}")
                    if author is not None and ccby is not None:
                        break
            if author is None:
                raise Exception(f"no author in {p}")
            if ccby is None:
                raise Exception(f"no license in {p}")
            authors[ccby].add(author)
            files[ccby].append(str(p))
    print(
        """Files: *
Copyright: 2012 - 2026 LDraw.org
License: CC-BY-4.0
"""
    )
    for ccby in ["CC-BY-2.0 and CC-BY-4.0", "CC-BY-2.0", "CC-BY-4.0"]:
        print("Files:")
        for p in sorted(files[ccby]):
            print(f" {p}")
        print("Copyright:")
        for a in sorted(authors[ccby]):
            print(f" {a}")
        print(f"License: {ccby}")
        print()
        print(f"num files with {ccby}: {len(files[ccby])}", file=sys.stderr)
    for ccby, p in [("CC-BY-2.0", "CAlicense.txt"), ("CC-BY-4.0", "CAlicense4.txt")]:
        print(f"License: {ccby}")
        with open(p) as f:
            for line in f:
                if line == "\n":
                    line = ".\n"
                print(f" {line}", end="")
        print()
    print(
        """Files: debian/*
Copyright: 2013-2025 Johannes Schauer Marin Rodrigues <josch@debian.org>
           2025-2026 Nicolas Schodet <nico@ni.fr.eu.org>
License: GPL-2+

License: GPL-2+
 On Debian systems the full text of the GNU General Public License
 version 2 can be found in the `/usr/share/common-licenses/GPL-2' file.
"""
    )


if __name__ == "__main__":
    main()
