Created
April 21, 2023 20:32
-
-
Save jlxip/b7f609ff31849f7d4ae7be10485f2901 to your computer and use it in GitHub Desktop.
From 49.4 MB to 13.8 MB of a compressed µlfs hdd.img
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -eu | |
# µlfs runtime module minimization | |
IMG=hdd.img | |
# Check (due to bash -e) | |
which zerofree | |
# Mount the image | |
LOOP="$(sudo losetup --partscan --show --find $IMG)" | |
PART="$LOOP"p1 | |
mkdir -p mnt/ | |
sudo mount $PART mnt/ | |
# Drop the script | |
DROPPED=/rmm.sh | |
echo '#!/bin/sh | |
# Get used modules | |
USED="$(cat /proc/modules | cut -d" " -f1 | xargs modinfo | grep filename)" | |
USED="$(echo "$USED" | rev | cut -d" " -f1 | rev)" | |
echo "$USED" | sort > /root/used.txt | |
# Get all modules | |
ALL="$(find /lib/modules -type f -name "*.ko.gz")" | |
echo "$ALL" | sort > /root/all.txt | |
# Substract | |
SUB="$(comm -3 /root/all.txt /root/used.txt)" | |
# Remove from root | |
echo "$SUB" | xargs rm -f | |
find /lib/modules -type d -empty -delete | |
# Now for the initramfs, extract | |
gzip -d /boot/initramfs.cpio.gz | |
mkdir /root/initramfs | |
cd /root/initramfs | |
cpio -idm -F /boot/initramfs.cpio | |
rm /boot/initramfs.cpio | |
# Clean | |
echo "$SUB" | while read line; do echo "/root/initramfs/$line"; done | \ | |
tail -n+2 | xargs rm -f | |
find ./lib/modules -type d -empty -delete | |
# Pack again | |
find . -print0 | cpio -o -H newc -0 | gzip --best > /boot/initramfs.cpio.gz | |
# Cleanup | |
rm -rf /root/all.txt /root/used.txt /root/initramfs $0 | |
' | sudo tee mnt/$DROPPED | |
sudo chmod +x mnt/$DROPPED | |
# Unmount | |
sudo umount mnt/ | |
sudo losetup -d $LOOP | |
# Wait | |
echo -e "\nScript dropped at $DROPPED" | |
echo "Please boot the disk and execute it" | |
echo "Then, power off and hit enter, or Ctrl-C to abort" | |
read | |
# Mount the loop device again | |
LOOP="$(sudo losetup --partscan --show --find $IMG)" | |
PART="$LOOP"p1 | |
# Zerofree | |
sudo zerofree $PART | |
# Unmount the loop device | |
sudo losetup -d $LOOP | |
# That's it! Compress with something in the lines of: | |
# xz -k -T`nproc` -v hdd.img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment