#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-only

set -e

# for initramfs-tools hook-functions
export DESTDIR=/run/initramfs
# for /usr/lib/dracut/dracut-install
export DESTROOTDIR=$DESTDIR
# initramfs-tools now requires this to be set
export verbose=n

# something already created shutdown initramfs
# same check is done by e.g. dracut-shutdown
# it is expected that any shutdown initramfs is good enough
#[ ! -x $DESTDIR/bin/sh ] || exit 0

#compare library
[ ! -f $DESTDIR/DoneEnd ] || exit 0

# /run may be mounted noexec,nosuid => fix it
# it should be a more normal/default filesystem post-pivot
# systemd-shutdownd pivot does not currently remount /run with these
# options
mount -o remount,exec /run

if [ -f $DESTDIR/DoneStart ];then
	newfile=0
	if [ -f $DESTDIR/filelist ];then
		for d in /usr/share/finalrd /etc/finalrd /run/finalrd
		do
    			if [ -d $d ];then
                    filelists=$(find $d -executable -name '*.finalrd')
				    echo $filelists
				    for file in $filelists
				    do
					    if [ "X$(grep "$file" $DESTDIR/filelist)" = "X" ];then
						    echo "no $file file"
						    newfile=1
					    fi
				    done
    			fi
		done
	fi

	if [ $newfile -eq 0 ];then
		echo "already do finalrd"
		exit 0
	else
		echo "need refinalrd"
		touch $DESTDIR/DoneEnd
	fi
else
	echo "need do finalrd"
	touch $DESTDIR/DoneEnd
fi


### SHUTDOWN SUPPORT ###
# systemd-shutdown already copy to /run/initramfs directory

### HOOKS SUPPORT ###
# Without initramfs-tools, hooks are not supported
[ -e /usr/share/initramfs-tools/hook-functions ] || exit 0
. /usr/share/initramfs-tools/hook-functions

for d in /usr/share/finalrd /etc/finalrd /run/finalrd
do
    if [ -d $d ]
    then
        run-parts -v --regex='^.*\.finalrd$' --arg=setup -- $d || true
        find $d -executable -name '*.finalrd' -exec cp -- "{}" $DESTDIR/lib/systemd/system-shutdown \;
    fi
done

ldconfig -r $DESTDIR
