#!/usr/bin/env bash

# WTF License 1.0 
# Author Bruno Friedmann tigerfoot (at) opensuse.org

# Usage : this script will create an optimized virtio initrd without
# lvm, crypt, gfx tool
# Edit the 2 devices you target to use 
# 
DEVBUILD='/dev/vg1/lvobsbuild'
DEVSWAP='/dev/vg1/lvobsswap'

nokms(){
sed -i '/^NO_KMS_IN_INITRD/s/no/yes/' /etc/sysconfig/kernel
}

kms(){
sed -i '/^NO_KMS_IN_INITRD/s/yes/no/' /etc/sysconfig/kernel
}

echo "cleanup /tmp"
rm -fr /tmp/initrd*

# Patch the virtio initrd
if [ -z "$1" ];then
export VER=`uname -r`
else
export VER="$1"
fi
export INITRD="/boot/initrd-$VER-virtio"
echo "Setting nokms"
nokms

echo "Building -virtio initrd ..."
"env" "rootfstype=ext4,resume=$DEVSWAP,rootdev=$DEVBUILD,udevtimeout=2,udev_timeout=2,nosplash,noluks" "mkinitrd" "-B" "-d" "$DEVBUILD" "-m" "ext4 btrfs binfmt_misc virtio_pci virtio_blk" "-k" "/boot/vmlinuz-$VER" "-i" "$INITRD"

ls -l $INITRD

echo "Setting kms"
kms

# copy the *.virtio initrd to /tmp
cp -vfa $INITRD /tmp/initrd-virtio.gz

# ungzip it gzip -d initrd
cd /tmp
mkdir initrd.build
gzip -d initrd-virtio.gz

cd initrd.build

# uncpio cpio -id < ../initrd
cpio -id < ../initrd-virtio

# remove luks.sh
rm -fv ./boot/71-luks.sh ./config/luks.sh
sed -i 's/71-luks\.sh//g' ./run_all.sh

# rebuild cpio find . | cpio --create --format='newc' > ../initrd
rm -fv ../initrd-virtio
echo "rebuilding initrd ..."
find . | cpio --create --format='newc' > ../initrd-virtio
cd ../
echo "Compressing initrd ..."
# Install pigz if you want to save half an hour of your life.
if [ -x /usr/bin/pigz ];then
 pigz -9v initrd-virtio
else
 gzip -9v initrd-virtio
fi
# copy to /boot
cp -v initrd-virtio.gz $INITRD

#Relinking initrd-virtio 
rm -f /boot/initrd-virtio
ln -s $INITRD /boot/initrd-virtio
echo "Done ..."

