#!/bin/sh -eu

. sh-functions

cd "$rootdir"

mkdir $verbose -p -- \
	./conf \
	./dev \
	./etc/modprobe.d \
	./etc/udev/rules.d \
	./"$kernel_modules_dir" \
	./lib/udev \
	./mnt \
	./root \
	./run \
	./proc \
	./sys \
	./tmp \
	./var/lock \
	#

printf '%s\n' "${VERSION-}" > ./.version

verbose "Copying files from libnss_files.so* ..."
for lib in /lib64 /lib; do
	[ ! -d "$lib" ] ||
		find $lib -mindepth 1 -maxdepth 1 \
			\( \
				-name 'libnss_files.so*' -o \
				-name 'libnss_dns.so*' \
			\) \
			-exec put-file . '{}' '+'
done

echo 'root:x:13957::::::'                        >./etc/shadow
echo 'root:*::'                                  >./etc/gshadow
echo '127.0.0.1 localhost.localdomain localhost' >./etc/hosts
echo ''                                          >./etc/resolv.conf

while IFS=: read name pass gid dummy; do
	[ -n "$name" ] && [ "$gid" -lt 500 ] ||
		continue
	printf '%s\n' "$name:$pass:$gid:$dummy"
done < /etc/group > ./etc/group

while IFS=: read name pass uid gid dummy; do
	[ -n "$name" ] && [ "$uid" -lt 500 ] ||
		continue
	printf '%s\n' "$name:$pass:$uid:$gid:$dummy"
done < /etc/passwd > ./etc/passwd

for n in protocols rpc services; do
	egrep -v '^[[:space:]]*(#.*)?$' /etc/$n > ./etc/$n ||:
done

cat >./etc/host.conf <<EOF
order hosts,bind
multi on
EOF

cat >./etc/nsswitch.conf <<EOF
passwd:    files
group:     files
shadow:    files
hosts:     files dns
networks:  files
rpc:       files
services:  files
protocols: files
EOF

[ -z "${PUT_DIRS-}"  ] || put-tree . $PUT_DIRS
[ -z "${PUT_FILES-}" ] || put-file . $PUT_FILES

:>>./etc/fstab

if [ ! -x ./bin/sh ]; then
	for n in bash dash mksh ash; do
		[ -x ./bin/$n ] || continue
		verbose "Setting $n as /bin/sh ..."
		ln -s $n ./bin/sh
		break
	done
fi

if [ -f /etc/modprobe.conf ]; then
	verbose "Copying /etc/modprobe.conf ..."
	put-file . /etc/modprobe.conf
fi

for d in lib etc; do
	if [ -d "/$d/modprobe.d" ]; then
		verbose "Copying files from $d/modprobe.d ..."
		find -L "/$d/modprobe.d" \
				-name '*.conf' \
			-exec cp -aLt ./etc/modprobe.d -- '{}' '+'
	fi

	if [ -d "/$d/udev/initramfs-rules.d" ]; then
		verbose "Copying files from /$d/udev/initramfs-rules.d ..."
		find -L "/$d/udev/initramfs-rules.d" \
				-name '*.rules' \
			-exec cp -aLt ./etc/udev/rules.d -- '{}' '+'
	fi
done

for n in builtin order; do
	[ ! -f "$kernel_modules_dir/modules.$n" ] ||
		cp -aLt ./"$kernel_modules_dir" -- "$kernel_modules_dir/modules.$n"
done
