#!/bin/sh
# Copyright 2020-2022  Jonas Smedegaard <dr@jones.dk>
# Copyright 2020-2021  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,
#  perl,

set -eu

SKIPFILES='skip|meta'

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

# omit files not copyright protected nor stating copyright or licensing
RE_omit='.*\.(ico)'

#1>&2 echo 'skip binary files without parsable metadata ...'
#RE_skip='.*\.(xls|pcl|xps)'
#find -type f -regextype posix-egrep -regex "^($RE_skip)$" -exec sh -c "echo 'License: UNKNOWN' > '{}:skip'" ';'

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

#RE_SKIP="$RE_omit|$RE_skip|$RE_meta"
RE_SKIP="$RE_omit|$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
