#!/bin/sh
# SPDX-FileCopyrightText: 2020-2026  Jonas Smedegaard <dr@jones.dk>
#
# SPDX-FileCopyrightText: 2020-2021  Purism, SPC
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Description: helper script to update copyright_hints
#
# Depends:
#  licensecheck,
#  libimage-exiftool-perl,
#  libipc-system-simple-perl,
#  perl,

set -eu

RE_hint='meta'

EXT_meta='otf ttf png'

ext2re() { perl -sE 'printf ".*\.(%s)", join "|", split " ", $e' -- -e="$1"; }
ext2opt() { perl -sE 'say map {" $o $_"} split " ", $e' -- -o="$1" -e="$2"; }

RE_meta=$(ext2re "$EXT_meta")${RE_meta:+|$RE_meta}
RE_debian='debian/(changelog|copyright(_hints)?|source/lintian-overrides)'
RE_hint='skip|meta'

# cleanup stray hint files from a previous run
find ./* -type f -regextype posix-egrep -regex "^\./.*:($RE_hint)$" -delete

echo 'extract metadata from binary files ...' 1>&2
exiftool '-textOut!' %d%f.%e:meta -short -short -recurse -extractEmbedded \
 $(ext2opt -ext "$EXT_meta") \
 -- ./*

RE_SKIP="$RE_meta"

# TODO: automate more of this manual cleanup:
#  * strip garbage copyright holders
#  * optionally merge equally licensed Files sections
#  * do "sort -k2 -k1,1 -u" on copyright holders
#  * merge copyright years for each copyright holder
# TODO: strip files matching glob in current (only, no later) section
_licensecheck() {
    perl -Mv5.36 -MGetopt::Long=:config,gnu_getopt \
    -MIPC::System::Simple=capture -MList::Util=uniq \
    -- - --hint="$RE_hint" "$@" <<'EOF' >> debian/copyright_hints
my %opt;
GetOptions ( \%opt, "merge-licenses",
    "hint=s", "check=s", "ignore=s", "shortname=s", "subset=s" );
my @subset = exists $opt{subset} ? split(" ", $opt{subset}) : ();
my $subset_globs = join( "\n ", @subset );
if    ( $subset_globs =~ /^[*]$/ )    { say STDERR "check default section(s) ..." }
elsif ( @subset and $opt{shortname} ) { say STDERR "check $opt{shortname} section(s) @subset ..." }
elsif (@subset)                       { say STDERR "check section(s) @subset ..." }
elsif ( $opt{shortname} )             { say STDERR "check $opt{shortname} section(s) ..." }
else                                  { say STDERR "check remaining upstream section(s) ..." }
my @cmd = ( qw(licensecheck --copyright --deb-machine --recursive --lines 0),
    "--check",  $opt{check}, "--ignore", $opt{ignore},
    ($opt{"merge-licenses"} ? "--merge-licenses" : ()), "--" );
say STDERR "@cmd *" if $ENV{DEBUG};
local $_ = capture( @cmd, glob "*" );
if ( !$ENV{NOGLOBMERGE} and grep /[*]/, @subset ) { s/^.*?\n\nFiles: \K.*?(?=\n\w)/$subset_globs/s }
elsif (@subset)                                   { s/^.*?\n\nFiles: \K/$subset_globs\n /s }
s/^.*?\n\n//s if exists $opt{subset} and (!@subset or $subset[0] ne "*");
s/^Files:\K /\n /mg;
s/^[C]opyright:\K /\n  /mg;
s/(?:(?<=^  )|(?<=\d{4})),\K (?=\d{4})//mg;
s/:(?:$opt{hint})$//mg if $opt{hint};
if ($opt{shortname}) { s/^License: \K(.*)/ join " and\/or ", uniq sort grep( !m{\AUNKNOWN\Z}, split(" and\/or ", $1), $opt{shortname} ) /mge }
print;
EOF
}

rm -f debian/copyright_hints

# initially, check all to know roughly what to group and in which order
#rm -f debian/copyright_hints
#_licensecheck --check '.*' --ignore "^($RE_SKIP|debian/.*)$"
#exit 0

# check generally
#  * omit non-copyright-protected Debian files
_licensecheck --subset '*' --check '.*' --ignore "^($RE_SKIP|debian/.*)$"
_licensecheck --subset 'debian/*' --check '^debian/' --ignore "^($RE_SKIP|debian/(changelog|copyright(_hints)?|source/lintian-overrides))$"

# cleanup hint files
find -type f -regextype posix-egrep -regex "^.*:($RE_hint)$" -delete
