#!/bin/sh
# Copyright 2020, 2022-2024  Jonas Smedegaard <dr@jones.dk>
# Copyright 2020, 2022       Purism, SPC
# Description: helper script to update copyright_hints
#
# 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 3, 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 program.  If not, see <http://www.gnu.org/licenses/>.

# Depends:
#  licensecheck,
#  libimage-exiftool-perl,

set -eu

SKIPFILES='skip|meta'

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

1>&2 echo 'skip binary files without parsable metadata ...'
RE_skip='.*\.(icns|ico|nib|pbxproj|plist|strings)'
find ./* -type f -regextype posix-egrep -regex "^\./($RE_skip)$" -exec sh -c 'echo "License: UNKNOWN" > "$1:skip"' shell {} ';'

1>&2 echo 'extract metadata from binary files ...'
EXT_meta='gif png tiff'
RE_meta=$(echo "$EXT_meta" | perl -aE '$"="|";say ".*\\.(@F)|Resource/Font/.*"') #"
exiftool '-textOut!' %d%f.%e:meta -short -short -recurse -extractEmbedded $(echo "$EXT_meta" | perl -aE 'say map {" -ext $_"} @F') -- ./*

RE_SKIP="$RE_skip|$RE_meta"

# skip non-copyright-protected Debian files
RE_debian='debian/(changelog|copyright(_hints)?|source/lintian-overrides)'

# check for copyright and licensing statements
licensecheck --copyright --deb-machine --recursive --lines 0 --check '.*' --ignore "^($RE_SKIP|$RE_debian)$" -- * > debian/copyright_hints

# tidy listing of diverted files
sed -i -e 's/:meta$//' -e 's/:skip$//' debian/copyright_hints

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