#!/usr/bin/env python3
# Copyright 2026 Johannes Schauer Marin Rodrigues <josch@debian.org>
# SPDX-License-Identifier: MIT

from collections import namedtuple
from pathlib import Path
import json
import sys

licensetexts = {
    "OFL-1.1": """
Copyright (c) 2015-2026, Renzhi Li (aka. Belleve Invis, belleve@typeof.net)

This Font Software is licensed under the SIL Open Font License, Version 1.1.

This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL

--------------------------


SIL Open Font License v1.1
====================================================


Preamble
----------

The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded, 
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.


Definitions
-------------

`"Font Software"` refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

`"Reserved Font Name"` refers to any names specified as such after the
copyright statement(s).

`"Original Version"` refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

`"Modified Version"` refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

`"Author"` refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.


Permission & Conditions
------------------------

Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1. Neither the Font Software nor any of its individual components,
   in Original or Modified Versions, may be sold by itself.

2. Original or Modified Versions of the Font Software may be bundled,
   redistributed and/or sold with any software, provided that each copy
   contains the above copyright notice and this license. These can be
   included either as stand-alone text files, human-readable headers or
   in the appropriate machine-readable metadata fields within text or
   binary files as long as those fields can be easily viewed by the user.

3. No Modified Version of the Font Software may use the Reserved Font
   Name(s) unless explicit written permission is granted by the corresponding
   Copyright Holder. This restriction only applies to the primary font name as
   presented to the users.

4. The name(s) of the Copyright Holder(s) or the Author(s) of the Font
   Software shall not be used to promote, endorse or advertise any
   Modified Version, except to acknowledge the contribution(s) of the
   Copyright Holder(s) and the Author(s) or with their explicit written
   permission.

5. The Font Software, modified or unmodified, in part or in whole,
   must be distributed entirely under this license, and must not be
   distributed under any other license. The requirement for fonts to
   remain under this license does not apply to any document created
   using the Font Software.



Termination
-----------

This license becomes null and void if any of the above conditions are
not met.


    DISCLAIMER
    
    THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
    OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
    COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
    DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
    OTHER DEALINGS IN THE FONT SOFTWARE.
""",
    "GPL-2+": """
This package 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 package 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, see <https://www.gnu.org/licenses/>

On Debian systems, the complete text of the GNU General
Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
""",
    "ISC": """
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""",
    "MIT": """
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.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
""",
    "0BSD": """
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
""",
    "BSD-3-Clause-adobe": """
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""",
    "Apache-2.0": """
On Debian systems the full text of the Apache-2.0 license can be found in
/usr/share/common-licenses/Apache-2.0.
""",
    "0BSD": """
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
""",
    "BSD-3-Clause": """
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The names of Kitware, Inc., the Insight Consortium, or the names of
   any consortium members, or of any contributors, may not be used to
   endorse or promote products derived from this software without
   specific prior written permission.
""",
    "BSD-2-Clause": """
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1) Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.

2) Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
""",
    "BSL-1.0": """
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
""",
    "BlueOak-1.0.0": """
# Blue Oak Model License

Version 1.0.0

## Purpose

This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.

## Acceptance

In order to receive this license, you must agree to its
rules.  The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.

## Copyright

Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.

## Notices

You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.

## Excuse

If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice.  If you do not do so, your license
ends immediately.

## Patent

Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.

## Reliability

No contributor can revoke this license.

## No Liability

***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
""",
    "MIT": """
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.
.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X
CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings in
this Software without prior written authorization from the X Consortium.
""",
    "Python-2.0": """
A. HISTORY OF THE SOFTWARE
==========================

Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.

In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation.  In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.

All Python releases are Open Source (see http://www.opensource.org for
the Open Source Definition).  Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.

    Release         Derived     Year        Owner       GPL-
                    from                                compatible? (1)

    0.9.0 thru 1.2              1991-1995   CWI         yes
    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
    1.6             1.5.2       2000        CNRI        no
    2.0             1.6         2000        BeOpen.com  no
    1.6.1           1.6         2001        CNRI        yes (2)
    2.1             2.0+1.6.1   2001        PSF         no
    2.0.1           2.0+1.6.1   2001        PSF         yes
    2.1.1           2.1+2.0.1   2001        PSF         yes
    2.1.2           2.1.1       2002        PSF         yes
    2.1.3           2.1.2       2002        PSF         yes
    2.2 and above   2.1.1       2001-now    PSF         yes

Footnotes:

(1) GPL-compatible doesn't mean that we're distributing Python under
    the GPL.  All Python licenses, unlike the GPL, let you distribute
    a modified version without making your changes open source.  The
    GPL-compatible licenses make it possible to combine Python with
    other software that is released under the GPL; the others don't.

(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
    because its license has a choice of law clause.  According to
    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
    is "not incompatible" with the GPL.

Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.


B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================

PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------

1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation;
All Rights Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS"
basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee.  This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.

8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.


BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------

BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1

1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an "AS IS"
basis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions.  Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee.  This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party.  As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.

7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.


CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------

1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee.  Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement.  This Agreement together with
Python 1.6.1 may be located on the Internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013.  This
Agreement may also be obtained from a proxy server on the Internet
using the following URL: http://hdl.handle.net/1895.22/1013".

3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.

7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee.  This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.

8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.

        ACCEPT


CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------

Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""",
    "WTFPL": """
            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (c) 2018 David Chambers <dc@davidchambers.me>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.
""",
    "Unicode-DFS-2016": """
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
See Terms of Use for definitions of Unicode Inc.'s Data Files and Software.

Unicode Data Files include all data files under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/,
http://www.unicode.org/ivd/data/, and
http://www.unicode.org/utility/trac/browser/.

Unicode Data Files do not include PDF online code charts under the directory
http://www.unicode.org/Public/.

Software includes any source code published in the Unicode Standard or under
the directories http://www.unicode.org/Public/,
http://www.unicode.org/reports/, http://www.unicode.org/cldr/data/,
http://source.icu-project.org/repos/icu/, and
http://www.unicode.org/utility/trac/browser/.

NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING,
INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA
FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO
BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT
AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR
SOFTWARE.

COPYRIGHT AND PERMISSION NOTICE

Copyright © 1991-2016 Unicode, Inc. All rights reserved. Distributed under the
Terms of Use in http://www.unicode.org/copyright.html.

Permission is hereby granted, free of charge, to any person obtaining a copy of
the Unicode data files and any associated documentation (the "Data Files") or
Unicode software and any associated documentation (the "Software") to deal in
the Data Files or Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or sell copies
of the Data Files or Software, and to permit persons to whom the Data Files or
Software are furnished to do so, provided that either

    (a) this copyright and permission notice appear with all copies of the Data Files or Software, or
    (b) this copyright and permission notice appear in associated Documentation.

THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD
PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN
THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR
SOFTWARE.

Except as contained in this notice, the name of a copyright holder shall not be
used in advertising or otherwise to promote the sale, use or other dealings in
these Data Files or Software without prior written authorization of the
copyright holder.
""",
}

header = """
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: fonts-iosevka
Upstream-Contact: Belleve Invis <belleve@typeof.net>
Source: https://github.com/be5invis/Iosevka
Files-Excluded:
 .gitattributes
 images
 node_modules/@biomejs/cli-linux-arm64/biome
 node_modules/@napi-rs/nice-linux-arm64-gnu/nice.linux-arm64-gnu.node
 node_modules/@napi-rs/nice-linux-arm64-musl/nice.linux-arm64-musl.node
 node_modules/harfbuzzjs/hb-subset.wasm
 node_modules/harfbuzzjs/hb.wasm
 node_modules/prettier/plugins/flow.js
 node_modules/prettier/plugins/flow.mjs
 node_modules/source-map/lib/mappings.wasm
"""


stanzas = {
    "*": ["2015-2026, Renzhi Li (aka. Belleve Invis, belleve@typeof.net)", "OFL-1.1"],
    "debian/*": ["2020-2026 Alex Myczko <tar@debian.org>", "GPL-2+"],
    "node_modules/@ot-builder/*": [
        "2019-2025 Shiyu He (aka. pal3love) https://github.com/ot-builder/monorepo",
        "MIT",
    ],
    "node_modules/argparse/*": [
        "1999-2001 Gregory P. Ward",
        "2002-2020 Python Software Foundation",
        "Python-2.0",
    ],
    "node_modules/cldr/3rdparty/cldr/common/rbnf/*.xml": [
        "Copyright © 1991-2024 Unicode, Inc.",
        "Unicode-DFS-2016",
    ],
    "node_modules/cldr/3rdparty/cldr/common/testData/personNameTest/*": [
        "Copyright © 2022-2024 Unicode, Inc.",
        "Unicode-DFS-2016",
    ],
    "node_modules/harfbuzzjs/test/fonts/noto/*": [
        "2015-2021 Google LLC. All Rights Reserved.",
        "OFL-1.1",
    ],
    "node_modules/ot-builder/*": [
        "2019-2025 Shiyu He (aka. pal3love) https://github.com/ot-builder/monorepo",
        "MIT",
    ],
    "node_modules/otb-ttc-bundle/*": [
        "2019-2025 Shiyu He (aka. pal3love) https://github.com/ot-builder/monorepo",
        "MIT",
    ],
    "node_modules/patel/*": ["Copyright (c) 2014 Belleve Invis", "MIT"],
    "node_modules/through/*": [
        "Dominic Tarr <dominic.tarr@gmail.com> (dominictarr.com)",
        "MIT or Apache-2.0",
    ],
    "node_modules/ts-command-line-args/*": [
        "Giles Roadnight <giles.roadnight@gmail.com>",
        "ISC",
    ],
    "node_modules/unicoderegexp/*": ["Copyright (c) 2013, One.com", "BSD-3-Clause"],
    "node_modules/@napi-rs/nice-linux-arm64-musl/*": [
        "LongYinan <lynweklm@gmail.com>",
        "MIT",
    ],
    "node_modules/@napi-rs/nice-linux-arm64-gnu/*": [
        "LongYinan <lynweklm@gmail.com>",
        "MIT",
    ],
    "node_modules/@biomejs/cli-linux-arm64/*": [
        "Emanuele Stoppa <my.burning@gmail.com>",
        "Victorien Elvinger <victorien@elvinger.fr>",
        "Sebastian McKenzie <sebmck@fb.com>",
        "Sebastian <853712+sebmck@users.noreply.github.com>",
        "Micha Reiser <micha@rome.tools>",
        "Carson McManus <dyc3@users.noreply.github.com>",
        "Denis Bezrukov <6227442+denbezrukov@users.noreply.github.com>",
        "l3ops <leops@users.noreply.github.com>",
        "Naoki Ikeguchi <me@s6n.jp>",
        "Arend van Beelen jr. <arend@arendjr.nl>",
        "Arend van Beelen jr. <arendjr@gmail.com>",
        "Sebastian <git@sebastian.barretomckenzie.com>",
        "Daniel Frederico Lins Leite <xunilrj@hotmail.com>",
        "Emanuele <my.burning@gmail.com>",
        "Sebastian McKenzie <sebastian@rome.tools>",
        "Ze-Zheng Wu <zezhengwu@proton.me>",
        "unvalley <38400669+unvalley@users.noreply.github.com>",
        "Victorien ELVINGER <victorien@elvinger.fr>",
        "Yasser Elassal <yassere@gmail.com>",
        "IWANABETHATGUY <iwanabethatguy@qq.com>",
        "YeonJuan <yeonjuan93@naver.com>",
        "Olivier Dusabimana <dusabima@adobe.com>",
        "Florent Cailhol <florent.cailhol@gmail.com>",
        "Daiki Nishikawa <nd.12021218@gmail.com>",
        "Maikel van Dort <maikel.van.dort@gmail.com>",
        "jfmcdowell <206422+jfmcdowell@users.noreply.github.com>",
        "github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>",
        "Võ Hoàng Long <78085736+vohoanglong0107@users.noreply.github.com>",
        "jer3m01 <jer3m01@jer3m01.com>",
        "Jon <jonegeland@gmail.com>",
        "Arend van Beelen jr <arendjr@gmail.com>",
        "EduardoLopes <EduardoLopesDS@gmail.com>",
        "Sebastian McKenzie <git@sebastian.barretomckenzie.com>",
        "Nicolas Hedger <649677+nhedger@users.noreply.github.com>",
        "zoomdong <1344492820@qq.com>",
        "Nicholas Yang <nicholas@rome.tools>",
        "macovedj <djmacovei@gmail.com>",
        "ty <62130798+togami2864@users.noreply.github.com>",
        "Zheyu Zhang <zheyuzhang03@gmail.com>",
        "Sebastian <sebastian@rome.tools>",
        "Justinas Delinda <8914032+minht11@users.noreply.github.com>",
        "Vasu Singh <vasucp1207@gmail.com>",
        "Paul Bouchon <mail@bitpshr.net>",
        "Lucas Weng <30640930+lucasweng@users.noreply.github.com>",
        "Victor <78874691+victor-teles@users.noreply.github.com>",
        "vladimir ivanov <vladoivan78@googlemail.com>",
        "Kevin Kelbie <notkelbie@outlook.com>",
        "Kaio Duarte <duartedossantos@gmail.com>",
        "Superchupu <53496941+SuperchupuDev@users.noreply.github.com>",
        "Matt Jones <mattjones701@gmail.com>",
        "Victor Hom <victor.hom16@gmail.com>",
        "Boshen <boshenc@gmail.com>",
        "Maikel van Dort <11695769+Netail@users.noreply.github.com>",
        "Antony David <antonydavid945@gmail.com>",
        "Marat Dulin <github-commit@maratd.com>",
        "Vinh Tran <daivinhtran.vt@gmail.com>",
        "Yusuke Abe <moonset20@gmail.com>",
        "bitpshr <mail@bitpshr.net>",
        "Eduardo Lopes <EduardoLopesDS@gmail.com>",
        "Victor Hom <victor@bluecore.com>",
        "Jamie Kyle <me@thejameskyle.com>",
        "Elton <eltonp3103@gmail.com>",
        "Jam Balaya <jambalaya.pyoncafe@outlook.jp>",
        "Takayuki Maeda <takoyaki0316@gmail.com>",
        "kaykdm <34934746+kaykdm@users.noreply.github.com>",
        "Aravind Reddy <reddy.aravind178@gmail.com>",
        "Gurwinder Singh <vargwin@gmail.com>",
        "JustBeYou <mihailferaru2000@gmail.com>",
        "Ryan Walker <ryan.matthew.walker@gmail.com>",
        "Yangshun Tay <tay.yang.shun@gmail.com>",
        "Keita Nonaka <iKonnyaku40@gmail.com>",
        "zinyando <brizdigital@gmail.com>",
        "Bertie690 <136088738+Bertie690@users.noreply.github.com>",
        "togami <62130798+togami2864@users.noreply.github.com>",
        "Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com>",
        "Anthony Shew <anthonyshew@gmail.com>",
        "Hiroki Okada <hirokiokada77@gmail.com>",
        "MINSEONG KIM <kwan0324@naver.com>",
        "Tu Shaokun <53142663+tt-a1i@users.noreply.github.com>",
        "Karl Persson <kalle.persson@grafana.com>",
        "Mareike Täubner <mareike.taeubner@procilon.de>",
        "Will Gardiner <gardiner.w@gmail.com>",
        "emanuele <my.burning@gmail.com>",
        "MIT OR Apache-2.0",
    ],
    "node_modules/aglfn/*": [
        "Chris Swithinbank <swithinbank@gmail.com>",
        "BSD-3-Clause-adobe",
    ],
}

licensemap = {
    "Apache-2": "Apache-2.0",
    "BSD": "BSD-3-Clause",  # memoizeasync
    "BSL": "BSL-1.0",  # clipper-lib
    "MIT/X11": "MIT",  # chainsaw, traverse, seq, hashish
}


def adddots(t):
    result = []
    for line in t.strip().split("\n"):
        line = line.replace("\t", "    ")  # replace tabs with whitespace
        line = line.rstrip()  # remove trailing whitespace
        if line == "":
            result.append(" .")
        else:
            result.append(" " + line)
    return "\n".join(result)


def e2s(e):
    if isinstance(e, dict):
        if "email" in e:
            return f"{e['name']} <{e['email']}>"
        else:
            return e["name"]
    else:
        return e


def license2copy(p):
    if not p.exists():
        return []
    result = []
    with p.open() as f:
        for i in range(10):
            line = f.readline()
            if "copyright" in line.lower():
                if line.startswith('THE SOFTWARE IS PROVIDED "AS IS"'):
                    continue
                if line.startswith(
                    "The above copyright notice and this permission notice"
                ):
                    continue
                if line.startswith("copyright notice and this permission notice"):
                    continue
                if line.startswith(
                    "The above copyright notice and this permission notice"
                ):
                    continue
                if line.startswith(
                    "Permission to use, copy, modify, and/or distribute"
                ):
                    continue
                if line.startswith("with or without fee is hereby granted"):
                    continue
                if line.startswith("Redistributions in binary form"):
                    continue
                if "Redistributions of source code" in line:
                    continue
                if "Redistributions in binary form" in line:
                    continue
                result.append(line.strip())
    return result


def main():
    for p in Path("./node_modules").rglob("package.json"):
        key = f"{p.parent}/*"
        if key in stanzas or f"{p.parent.parent}/*" in stanzas:
            continue
        with p.open() as f:
            pkgjson = json.load(f)
        if pkgjson in [
            {"type": "commonjs"},
            {"type": "module"},
            {"main": "."},
            {"main": "./"},
            {"name": "baz", "main": "quux.js"},
            {"main": "wrong.js"},
            {"name": "browser_field", "main": "a", "browser": "b"},
            {"name": "invalid_main", "main": ["why is this a thing", "srsly omg wtf"]},
            {"name": "false_main", "main": False},
            {"main": "bar.js"},
            {"main": "main.js"},
        ]:
            continue
        stanzas[key] = []
        if "author" in pkgjson:
            if isinstance(pkgjson["author"], list):
                stanzas[key].extend([e2s(d) for d in pkgjson["author"]])
            else:
                stanzas[key].append(e2s(pkgjson["author"]))
        if "maintainers" in pkgjson:
            stanzas[key].extend([e2s(d) for d in pkgjson["maintainers"]])
        if "contributors" in pkgjson:
            stanzas[key].extend([e2s(d) for d in pkgjson["contributors"]])
        for ln in ["license", "LICENSE", "license.md", "LICENSE.md"]:
            stanzas[key].extend(license2copy(p.parent / ln))
        if not stanzas[key]:
            raise Exception(f"no maintainers for {p}")
        stanzas[key] = sorted(set(stanzas[key]))

        if "licenses" in pkgjson:
            stanzas[key].append(" or ".join([l["type"] for l in pkgjson["licenses"]]))
        elif "license" in pkgjson:
            if isinstance(pkgjson["license"], dict):
                stanzas[key].append(pkgjson["license"]["type"])
            else:
                stanzas[key].append(pkgjson["license"])
        else:
            raise Exception(f"no license for {p}")

    licensenames = set()
    print(header.strip())
    print()

    found_non_matching = False
    for p in stanzas:
        if not list(Path(".").glob(p)):
            print(f"Not matching anything: {p}", file=sys.stderr)
            found_non_matching = True
    if found_non_matching:
        exit(1)

    for p in sorted(stanzas):
        print(f"Files: {p}")
        print("Copyright:")
        for copy in stanzas[p][:-1]:
            print(f" {copy}")
        licenses = stanzas[p][-1]
        for sep in ["or", "OR", "and", "AND"]:
            if f" {sep} " in licenses:
                licenses = [licensemap.get(l, l) for l in licenses.split(f" {sep} ")]
                licensenames.update(licenses)
                licenses = f" {sep.lower()} ".join(licenses)
                break
        else:
            licenses = licensemap.get(licenses, licenses)
            licensenames.add(licenses)
        print(f"License: {licenses}")
        print()

    used_licenses = set()
    for l in sorted(licensenames):
        l = licensemap.get(l, l)
        if l not in licensetexts:
            raise Exception(f"unknown license: {l}")
        print(f"License: {l}")
        print(adddots(licensetexts[l]))
        print()
        used_licenses.add(l)
    if set(licensetexts) - used_licenses:
        print(f"never used: {set(licensetexts) - used_licenses}", file=sys.stderr)
        exit(1)


if __name__ == "__main__":
    main()
