##!/bin/bash
# This script takes a list of packages by reading the *.packages file of build results
# and extracts their license files into a new RPM package.

# You need to change the call to combine in dump_requires manually
ARCHS="x86_64 ppc64le s390x"

dump_requires() {
	tmpdir="$(mktemp -d)"
	pushd "${tmpdir}" >/dev/null

	for arch in $ARCHS; do
		#for i in /dist/ibs/home\:/favogt\:/SLE-12-SP4/images/*${arch}*.packages; do
		for i in $OLDPWD/../*-image/binaries/*${arch}*.packages; do
			cut -d\| -f1 "${i}" | sort -u >> "${arch}"
		done
	done

	combine x86_64 and ppc64le | combine - and ppc64le | sort -u | tee common | awk '{ printf "BuildRequires: %s\n", $1 }'

        for arch in $ARCHS; do
		echo "%ifarch ${arch}"
		combine "${arch}" not common | awk '{ printf "BuildRequires: %s\n", $1 }'
		echo "%endif"
	done

	popd >/dev/null
	rm -rf "${tmpdir}"
}

cat > base-container-licenses.spec <<EOF
#
# spec file for package base-container-licenses
#
# Copyright (c) 2018 SUSE LINUX GmbH, Nuernberg, Germany.
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.

Name:           base-container-licenses
Version:        3.0
Release:        0
Summary:        Licenses for packages included in base container images
License:        MIT
Group:          Documentation/Other
URL:            https://www.suse.com/de-de/licensing/eula
BuildRequires:  fdupes
ExclusiveArch:  ${ARCHS}
# Not present in OBS
#!BuildIgnore:  gpg-pubkey
# These packages cause conflicts otherwise
# Prevent a build loop
#!BuildIgnore:  base-container-licenses
$(dump_requires)
EOF

cat >> base-container-licenses.spec <<"EOF"

%description
This package contains licenses for all packages included in the base container images.

%prep

%build

%install
pushd %{_datadir}/doc/packages/
for pkg in *; do
        destdir="%{buildroot}%{_datadir}/licenses/base-container/${pkg}/"

        found=0
        pushd "${pkg}"
	for filename in LICENSE* COPYING* COPYRIGHT* AUTHORS*; do
		[ ! -f "${filename}" ] && continue
		mkdir -p "${destdir}"
		cp "${filename}" "${destdir}"
		found=1
	done
        popd

	if [ "${found}" -ne "1" ]; then
		pkglicense="$(rpm -q --qf '%%{license}' -f ${pkg})" || pkglicense="$(rpm -q --qf '%%{license}' -f ${pkg}/* | head -n1)"
		echo "Package ${pkg} has no license file (license \"${pkglicense}\")."
	fi
done
popd

%fdupes %{buildroot}

%files
%{_datadir}/licenses/base-container

%changelog
EOF

