#!/bin/bash
# Usage: /tools/repack-initrd.sh /path/to/initrd-armv8

set -euo pipefail

initrd="${1:-}"

if [[ -z "$initrd" ]]; then
    echo "Usage: $0 /path/to/initrd-file"
    exit 1
fi

if [[ ! -f "$initrd" ]]; then
    echo "Error: '$initrd' not found."
    exit 1
fi

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

echo ">>> Unpacking initrd: $initrd"
cd "$tmpdir"
xz -dc "$initrd" | cpio -idm

echo
echo ">>> The initrd has been unpacked to:"
echo "    $tmpdir"
echo ">>> Make any changes you need, then press ENTER to continue..."
read -r

echo ">>> Repacking..."
find . | cpio -o -H newc | xz -9 --check=crc32 > "${initrd}"

read -p "Press ENTER to reboot or CTRL-C to quit"
reboot
