#!/bin/bash -xe
# Create initrd from a Gentoo Minimal Install CD for PXE boot
# Note. Embedding the squashfs image into the ramdisk is quite a dirty workaround
# link from 2008: http://blog.dastrup.com/?p=12
# link from 2010: https://ercpe.de/blog/how-to-boot-a-gentoo-livecd-via-pxe

print-usage() {
  echo "Usage: $0 <output-dir> <gentoo-iso>" >&2
}

# Example Invocation
# ./pxe-craft-initrd gentoopxe install-amd64-minimal-20190327T214503Z.iso

outdir="$1"
image="$2"
tmp="$outdir/tmp"

if [ $(id -u) -ne "0" ]; then
  echo "You must run as root or with sudo. This is necessary for the loop mount" && 
  print-usage &&
  exit 2
fi

test -z "$outdir" -o -z "$image" && print-usage && exit 1
test -e "$tmp" && echo "Temporary path '$tmp' already exists." >&2 && exit 1

iso="$tmp/iso"
initrd="$tmp/initrd.dir"

# prepare directories
mkdir -p "$outdir" "$tmp" "$iso" "$initrd/mnt/cdrom"

# extract files from ISO image
mount -o ro,loop "$image" "$iso"
cp "$iso"/{image.squashfs,boot/gentoo,boot/gentoo.igz} "$tmp"
umount "$iso"

# rename kernel
mv "$tmp/gentoo" "$tmp/kernel"

# patch initramfs and add squashfs to it
ls -la "$tmp/gentoo.igz"
xz -dc "$tmp/gentoo.igz" | ( cd "$initrd" && cpio -id )
cat >"${tmp}"/patch <<'EOF'
--- init.orig	2019-03-29 11:27:49.383915780 +0300
+++ init	2019-03-29 11:29:25.642114271 +0300
@@ -491,10 +491,6 @@
 		CHROOT=${NEW_ROOT}
 	fi
 
-	if [ /dev/nfs != "$REAL_ROOT" ] && [ sgimips != "$LOOPTYPE" ] && [ 1 != "$aufs" ] && [ 1 != "$overlayfs" ]; then
-		bootstrapCD
-	fi
-
 	if [ "${REAL_ROOT}" = '' ]
 	then
 		warn_msg "No bootable medium found. Waiting for new devices..."
@@ -636,7 +632,7 @@
 		else
 			bad_msg "Block device ${REAL_ROOT} is not a valid root device..."
 			REAL_ROOT=""
-			got_good_root=0
+			got_good_root=1
 		fi
 	done
 
@@ -718,8 +714,6 @@
 	[ -z "${LOOP}" ] && find_loop
 	[ -z "${LOOPTYPE}" ] && find_looptype
 
-	cache_cd_contents
-
 	# If encrypted, find key and mount, otherwise mount as usual
 	if [ -n "${CRYPT_ROOT}" ]
 	then
EOF
patch -d "$initrd" -p0 <"$tmp"/patch || true
cp "$tmp/image.squashfs" "$initrd/mnt/cdrom"
( cd "$initrd" && find . -print | cpio -o -H newc | pigz -9 -c - ) > "$tmp/initrd"

mv "$tmp"/{kernel,initrd} "$outdir"
rm -rf "$tmp"
ls -lkF "$outdir/kernel" "$outdir/initrd"
