Clean up on error

This commit is contained in:
Fierelier 2022-05-20 18:02:59 +02:00
parent 451230a66b
commit d43b788465

View File

@ -1,63 +1,76 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -e set -e
export DISK_IMAGE="$2" if
export ROOT_MOUNT="$OPUS_OUTPUT/mount" export DISK_IMAGE="$2"
export ROOT_MOUNT="$OPUS_OUTPUT/mount"
# Get the approximate size required for the image # Get the approximate size required for the image
export DISK_SIZE=$(du -sb "$1" | cut -f1) export DISK_SIZE=$(du -sb "$1" | cut -f1)
# Add 256MB for SWAP, and 700MB for overhead # Add 256MB for SWAP, and 700MB for overhead
export DISK_SIZE=$(( $DISK_SIZE + ( 256 * 1000000 ) + ( 700 * 1000000 ) )) export DISK_SIZE=$(( $DISK_SIZE + ( 256 * 1000000 ) + ( 700 * 1000000 ) ))
# Add size of additional files # Add size of additional files
export DISK_SIZE=$(( $DISK_SIZE + $(du -sb "$OPUS_HOME/input/root-image" | cut -f1) )) export DISK_SIZE=$(( $DISK_SIZE + $(du -sb "$OPUS_HOME/input/root-image" | cut -f1) ))
# Create and mount disk # Create and mount disk
fallocate -l $DISK_SIZE "$DISK_IMAGE" fallocate -l $DISK_SIZE "$DISK_IMAGE"
export DISK_LOOP="$(losetup --show -f -P "$DISK_IMAGE")" export DISK_LOOP="$(losetup --show -f -P "$DISK_IMAGE")"
# Partition disk # Partition disk
( (
echo n echo n
echo e echo e
echo echo
echo echo
echo +256M echo +256M
echo t echo t
echo swap echo swap
echo n echo n
echo p echo p
echo echo
echo echo
echo echo
echo t echo t
echo echo
echo linux echo linux
echo w echo w
echo echo
echo echo
) | fdisk "$DISK_LOOP" ) | fdisk "$DISK_LOOP"
# Format partions # Format partions
mkswap "${DISK_LOOP}p1" mkswap "${DISK_LOOP}p1"
mkfs.ext4 "${DISK_LOOP}p2" mkfs.ext4 "${DISK_LOOP}p2"
# Mount root # Mount root
mkdir "$ROOT_MOUNT" mkdir "$ROOT_MOUNT"
mount "${DISK_LOOP}p2" "$ROOT_MOUNT" mount "${DISK_LOOP}p2" "$ROOT_MOUNT"
# Add files # Add files
dupe "$1/." "$ROOT_MOUNT" dupe "$1/." "$ROOT_MOUNT"
# Make fstab # Make fstab
echo "UUID=$(blkid -o value -s UUID "${DISK_LOOP}p1") none swap sw 0 0" >"$ROOT_MOUNT/etc/fstab" echo "UUID=$(blkid -o value -s UUID "${DISK_LOOP}p1") none swap sw 0 0" >"$ROOT_MOUNT/etc/fstab"
echo "UUID=$(blkid -o value -s UUID "${DISK_LOOP}p2") / ext4 errors=remount-ro 0 1" >>"$ROOT_MOUNT/etc/fstab" echo "UUID=$(blkid -o value -s UUID "${DISK_LOOP}p2") / ext4 errors=remount-ro 0 1" >>"$ROOT_MOUNT/etc/fstab"
# Set up GRUB and misc # Set up GRUB and misc
fchroot "$ROOT_MOUNT" "/setupdisk" fchroot "$ROOT_MOUNT" "/setupdisk"
# Clear logs # Clear logs
find "$ROOT_MOUNT/var/log" -type f -delete find "$ROOT_MOUNT/var/log" -type f -delete
# Unmount root # Unmount root
umount -l "$ROOT_MOUNT" umount -l "$ROOT_MOUNT"
rmdir "$ROOT_MOUNT" rmdir "$ROOT_MOUNT"
losetup -d "$DISK_LOOP" losetup -d "$DISK_LOOP"
then
set +e
else
set +e
echo
echo Script execution ended due to error. Cleaning up...
umount -l "$ROOT_MOUNT"
rmdir "$ROOT_MOUNT"
losetup -d "$DISK_LOOP"
echo Script execution ended due to error.
exit 1
fi