#!/bin/bash -efu
# SPDX-License-Identifier: GPL-3.0-or-later

. sh-functions

PROCFS_PATH="${PROCFS_PATH:-/proc}"
SYSFS_PATH="${SYSFS_PATH:-/sys}"
reportdir="$workdir/report"

c=/
progress()
{
	case "$1" in
		'/') c='-' ;;
		'-') c='\' ;;
		'\') c='|' ;;
		'|') c='/' ;;
	esac
	# shellcheck disable=SC2169
	echo -en "\rPlease wait ... $1 "
}

copy()
{
	find -P "$@" -regextype egrep \! -type d |
	while read -r filename; do
		progress "$c"
		mkdir -p -- "$reportdir/${filename%/*}"
		cp -d --preserve=all -- \
			"$filename" "$reportdir/${filename%/*}"/ 2>/dev/null ||:
	done
	find -P "$@" -type d -empty -exec mkdir -p -- '{}' '+' ||:
}

progress "$c"
mkdir -p -- \
	"$reportdir"/boot \
	"$reportdir"/etc \
	"$reportdir"/"$SYSFS_PATH" \
	"$reportdir"/"$PROCFS_PATH/self" \
#

if [ -f "${KERNEL_CONFIG-}" ]; then
	cp -a \
		"$KERNEL_CONFIG" \
		"$reportdir"/boot/
	progress "$c"
fi

kver="$(uname -r)" ||:
if [ -n "$kver" ]; then
	find "/lib/modules/$kver" -mindepth 1 -maxdepth 1 -type f -name 'modules.*' |
	while read -r filename; do
		copy "$filename"
	done
fi

mkdir -p -- "$reportdir"/dev
LANG=C find /dev -xdev -a \! -type d -exec ls -lad '{}' '+' >"$reportdir"/dev/list
progress "$c"

(
	export LANG=C;
	find /dev -xdev -a \! -type d -exec stat -L -c '%A %t %T %n' '{}' '+' 2>/dev/null |
		grep -e '^[cb]' |
		sort >"$reportdir"/dev/devlist
) ||
	rm -f -- "$reportdir"/dev/devlist
progress "$c"

blkid -c /dev/null --no-encoding --output export |
	sed -r -e 's/^([^=]+)=/\1\t/' \
	       -e '${ s/^.*/&\n/ }' \
	       >"$reportdir"/etc/blkid.out1
findmnt -v --direction forward --pairs --output-all  |
	sed -r -e 's/" /"\n/g' -e 's/$/\n/' |
	sed -r -e 's/^([^=]+)="(.*)"$/\1\t\2/' \
	       >"$reportdir"/etc/findmnt.out1
progress "$c"

copy \
	/etc/fstab \
	"$PROCFS_PATH/cmdline" \
	"$PROCFS_PATH/config.gz" \
	"$PROCFS_PATH/cpuinfo" \
	"$PROCFS_PATH/crypto" \
	"$PROCFS_PATH/devices" \
	"$PROCFS_PATH/filesystems" \
	"$PROCFS_PATH/mdstat" \
	"$PROCFS_PATH/modules" \
	"$PROCFS_PATH/mounts" \
	"$PROCFS_PATH/partitions" \
	"$PROCFS_PATH/self/mountinfo" \
	"$PROCFS_PATH/self/mounts" \
	"$PROCFS_PATH/self/mountstats" \
	"$PROCFS_PATH/sys" \
	"$PROCFS_PATH/version" \
	"$SYSFS_PATH/block" \
	"$SYSFS_PATH/bus" \
	"$SYSFS_PATH/class" \
	"$SYSFS_PATH/dev" \
	"$SYSFS_PATH/devices" \
	"$SYSFS_PATH/firmware" \
	"$SYSFS_PATH/module" \
#

[ -z "${VERSION-}" ] ||
	printf '%s\n' "$VERSION" > "$reportdir"/.version
progress "done"
echo

compress="cat"
compargs=()
suffix=

if compress="$(type -P xz)"; then
	compargs=("-9")
	suffix=".xz"
elif compress="$(type -P bzip2)"; then
	compargs=("-9")
	suffix=".bz2"
elif compress="$(type -P gzip)"; then
	compargs=("-9")
	suffix=".gz"
fi

outfile="$PWD/make-initrd-bugreport-$(date +"%Y%m%d").tar$suffix"

cd "$workdir"
tar -cf - report | "$compress" "${compargs[@]}" >"$outfile"

printf '\nPlease submit %s to authors\n\n' "$outfile"
