#!/bin/bash
# Generates a list suitable for gen_init_cpio
# Author: Peter Lekensteyn <lekensteyn@gmail.com>
# License: GPLv3+

busybox="$1"
out="$2"
listname=list
list="$out/$listname"

if [ -z "$busybox" -o -z "$out" ]; then
	echo "Usage: $0 busybox-binary output-dir"
	echo "output-dir/$listname should be used with CONFIG_INITRAMFS_SOURCE"
	echo "Existing files in output-dir are not overwritten and included in"
	echo "the final image, with the current mode, but owned by root:root."
	exit 1
fi

if [ ! -s "$busybox" ]; then
	echo "$busybox is not contain a valid path to a busybox binary"
	echo "Perhaps you forgot to run make"
	exit 1
fi

mkdir -p "$out"
if [ ! -d "$out" ]; then
	echo "Cannot create output directory $out"
	exit 1
fi

add() {
	mkdir -p "$out/$(dirname "$1")"
	echo "file /$1 $out/$@" >> "$list"
	# only create new files
	if [ -e "$out/$1" ]; then
		echo "skipping $1"
	else
		echo "Creating $1"
		cat > "$out/$1"
	fi
}

### generate actual list
cat > "$list" <<EOF
dir /dev 755 0 0
nod /dev/console 600 0 0 c 5 1
#nod /dev/ttyS0 660 0 0 c 4 64
dir /root 700 0 0
dir /sbin 755 0 0
dir /bin 755 0 0
dir /usr 755 0 0
dir /usr/sbin 755 0 0
dir /usr/bin 755 0 0
dir /etc 755 0 0
dir /proc 755 0 0
dir /sys 755 0 0
dir /tmp 755 0 0
slink /var /tmp 755 0 0
slink /bin/sh busybox 755 0 0

EOF

add bin/busybox 755 0 0 < "$busybox"

add etc/passwd 644 0 0 <<X
root:x:0:0:root:/root:/bin/ash
daemon:*:1:1:daemon:/var:/bin/false
nobody:*:65534:65534:nobody:/var:/bin/false
X

add etc/group 644 0 0 <<X
root:x:0:
daemon:x:1:
nogroup:x:65534:
X

add etc/shadow 640 0 0 <<X
root:x:0:0:99999:7:::
nobody:*:0:0:99999:7:::
X

add etc/fstab 644 0 0 <<X
proc /proc proc nosuid,noexec,nodev 0 0
sysfs /sys sysfs nosuid,noexec,nodev 0 0
devtmpfs /dev devtmpfs mode=0755,nosuid 0 0
X

add etc/inittab 644 0 0 <<X
ttyS0::askfirst:/bin/ash --login
X

add init 755 0 0 <<X
#!/bin/sh
echo Starting init
/bin/busybox --install -s
mount -a
mkdir -m755 /dev/pts
mount -t devpts -o mode=620 devpts /dev/pts
exec init
X

# DNS
add etc/resolv.conf 644 0 0 <<X
nameserver 8.8.8.8
nameserver 8.8.4.4
X

add etc/hosts 644 0 0 <<X
127.0.0.1 localhost
X

# add other files
addo() {
	local ftype mode res
	ftype="$1"
	res="$2"

	# strip current directory marker
	res="${res#.}"

	# skip existing entries to preserve mode and ownership
	grep -qF "$ftype $res " "$list" && return 1

	mode="$(stat -c'%a' "$out$res")"

	# append file/dir owned by root:root
	echo "Adding $ftype $res with mode $mode"
	case $ftype in
	  file)	echo "file $res $out$res $mode 0 0" >> "$list" ;;
	  dir)	echo "dir $res $mode 0 0" >> "$list" ;;
	esac
	return 0
}

(cd "$out";find . ! -name . ! -path "./$listname" -type d) | while read dir; do
	addo dir "$dir"
done

(cd "$out";find . ! -path "./$listname" -type f) | while read file; do
	addo file "$file"
done
