1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #!/bin/bash # # Copy root filesystem into an existing raspberry pi image. # We take over the kernel modules and firmware files from # the existing image, as those are tightly belonging to # the kernel of this image. # # Note1: that we also change the uuids of the disks during this step. # # Note2: This way the bootloader and kernel from the existing # image is used. # # Note3: We intentionally don't use the result of mktemp # directly to reduce the risk of damaging the host filesystem. # output="$1" [ "x${output}" == "x" ] && output="raspbian.img" # download image [ ! -f ../${output} ] && (wget --output-document=../raspbian.zip 'https://downloads.raspberrypi.org/raspbian_lite_latest' && unzip -p ../raspbian.zip > ../${output}) || true # copy filesystem and change uuids d=$(basename $(mktemp -d)); f=$(basename $(mktemp /tmp/XXXXXXXXXX.tar)); l=$(sudo kpartx -l ../${output} | sed -n '/loop/ s,.*/dev/\(loop[0-9]\+\).*,\1, p;q;'); [ "x${d}" != "x" ] && sudo kpartx -as ../${output} && sudo mount /dev/mapper/${l}p2 /tmp/${d} && sed -i "s,PARTUUID=[^ ]*\(.*vfat\),PARTUUID=$(sudo blkid /dev/mapper/${l}p1 -s PARTUUID -o value)\1," etc/fstab && sed -i "s,PARTUUID=[^ ]*\(.*ext4\),PARTUUID=$(sudo blkid /dev/mapper/${l}p2 -s PARTUUID -o value)\1," etc/fstab && (cd /tmp/${d}; sudo tar -cf /tmp/${f} {lib/firmware,lib/modules,dev}) && sudo rm -Rf /tmp/${d}/* && sudo tar -cf - . | (cd /tmp/${d}/; sudo tar -xf -) && (cd /tmp/${d}; sudo tar -xf /tmp/${f}) && sudo umount /tmp/${d} && sudo kpartx -d ../${output} && rmdir /tmp/${d}; rm /tmp/${f} # modify command line in boot partition d=$(basename $(mktemp -d)); l=$(sudo kpartx -l ../${output} | sed -n '/loop/ s,.*/dev/\(loop[0-9]\+\).*,\1, p;q;'); [ "x${d}" != "x" ] && sudo kpartx -as ../${output} && sudo mount /dev/mapper/${l}p1 /tmp/${d} && sed -i 's| init=/usr/lib/raspi-config/init_resize.sh||' /tmp/${d}/cmdline.txt && sed -i 's| quiet||' /tmp/${d}/cmdline.txt && sed -i 's|#\(dtparam=spi\)|\1|' /tmp/${d}/config.txt && sed -i 's|#\(dtparam=i2c\)|\1|' /tmp/${d}/config.txt && sudo umount /tmp/${d} && sudo kpartx -d ../${output} && rmdir /tmp/${d} |