#!/usr/bin/env bash
set -Eeuo pipefail

thisDir="$(dirname "$(readlink -f "$BASH_SOURCE")")"
source "$thisDir/.constants.sh" \
	'<target-dir>' \
	'rootfs'

eval "$dgetopt"
while true; do
	flag="$1"; shift
	dgetopt-case "$flag"
	case "$flag" in
		--) break ;;
		*) eusage "unknown flag '$flag'" ;;
	esac
done

targetDir="${1:-}"; shift || eusage 'missing target-dir'
[ -n "$targetDir" ]

IFS=$'\n'; set -o noglob
slimExcludes=( $(grep -vE '^#|^$' "$thisDir/.slimify-excludes" | sort -u) )
set +o noglob; unset IFS

dpkgCfgFile="$targetDir/etc/dpkg/dpkg.cfg.d/docker"
mkdir -p "$(dirname "$dpkgCfgFile")"
{
	echo '# This is the "slim" variant of the Debian base image.'
	echo '# Many files which are normally unnecessary in containers are excluded,'
	echo '# and this configuration file keeps them that way.'
} > "$dpkgCfgFile"

neverExclude='/usr/share/doc/*/copyright'
for slimExclude in "${slimExcludes[@]}"; do
	{
		echo
		echo "# dpkg -S '$slimExclude'"
		if dpkgOutput="$("$thisDir/debuerreotype-chroot" "$targetDir" dpkg -S "$slimExclude" 2>&1)"; then
			echo "$dpkgOutput" | sed 's/: .*//g; s/, /\n/g' | sort -u | xargs
		else
			echo "$dpkgOutput"
		fi | fold -w 76 -s | sed 's/^/#  /'
		echo "path-exclude $slimExclude"
	} >> "$dpkgCfgFile"

	if [[ "$slimExclude" == *'/*' ]]; then
		if [ -d "$targetDir/$(dirname "$slimExclude")" ]; then
			# use two passes so that we don't fail trying to remove directories from $neverExclude
			# this is our best effort at implementing https://sources.debian.net/src/dpkg/stretch/src/filters.c/#L96-L97 in shell

			# step 1 -- delete everything that doesn't match "$neverExclude" and isn't a directory or a symlink
			"$thisDir/debuerreotype-chroot" "$targetDir" \
				find "$(dirname "$slimExclude")" \
					-mindepth 1 \
					-not -path "$neverExclude" \
					-not \( -type d -o -type l \) \
					-delete

			# step 2 -- repeatedly delete any dangling symlinks and empty directories until there aren't any
			# (might have a dangling symlink in a directory which then makes it empty, or a symlink to an empty directory)
			while [ "$(
				"$thisDir/debuerreotype-chroot" "$targetDir" \
					find "$(dirname "$slimExclude")" \
						-mindepth 1 \( -empty -o -xtype l \) \
						-delete -printf '.' \
					| wc -c
			)" -gt 0 ]; do true; done
		fi
	else
		"$thisDir/debuerreotype-chroot" "$targetDir" rm -f "$slimExclude"
	fi
done
{
	echo
	echo '# always include these files, especially for license compliance'
	echo "path-include $neverExclude"
} >> "$dpkgCfgFile"
chmod 0644 "$dpkgCfgFile"
