98 lines · bash
1#!/bin/bash2 3set -e4 5print_usage() {6 echo "Usage: $(basename $0) [options]"7 echo -e "Creates a Ubuntu root file system image.\n"8 echo -e " --help\t\t\tDisplay this information."9 echo -e " --arch {armhf|arm64}\t\tSelects architecture of rootfs image."10 echo -e " --distro {bionic|focal}\tSelects Ubuntu distribution of rootfs image."11 echo -e " --size n{K|M|G}\t\tSets size of rootfs image to n Kilo, Mega or Giga bytes."12 exit "$1"13}14 15invalid_arg() {16 echo "ERROR: Unrecognized argument: $1" >&217 print_usage 118}19 20update_repositories() {21 echo -e "\nUpdating apt repositories. "22 echo -e "\nPress 'y' to continue or any other key to exit..."23 read -s -n 1 user_input24 if [[ $user_input == 'Y' ]] || [[ $user_input == 'y' ]]; then25 sudo apt update26 else27 exit28 fi29}30 31# Parse options32while [[ $# -gt 0 ]]; do33 case "${END_OF_OPT}${1}" in34 --help) print_usage 0 ;;35 --arch) rfs_arch=$2; shift;;36 --distro) rfs_distro=$2; shift;;37 --size) rfs_size=$2; shift;;38 *) invalid_arg "$1" ;;39 esac40 shift41done42 43if [ -z "$rfs_arch" ]; then44 echo "Missing architecture"45 print_usage 146fi47if [ -z "$rfs_distro" ]; then48 echo "Missing distribution"49 print_usage 150fi51if [ -z "$rfs_size" ]; then52 echo "Missing size"53 print_usage 154fi55 56if [[ "$rfs_arch" != "arm64" && "$rfs_arch" != "armhf" ]]; then57 echo "Invalid architecture: $rfs_arch"58 print_usage 159fi60 61pat='^[0-9]+[K|M|G]$'62if [[ ! $rfs_size =~ $pat ]]; then63 echo "Invalid size: $rfs_size"64 print_usage 165fi66 67update_repositories68 69echo "Installing build dependencies ..."70sudo apt-get install debootstrap qemu-user-static schroot qemu-utils71 72image_name=$rfs_distro-$rfs_arch-"rootfs"73echo "Creating $rfs_distro ($rfs_arch) root file system ..."74echo "Image name: $image_name.img"75echo "Image size: $rfs_size"76 77qemu-img create $image_name.img $rfs_size78 79mkfs.ext4 $image_name.img80mkdir $image_name.dir81sudo mount -o loop $image_name.img $image_name.dir82 83sudo qemu-debootstrap --arch $rfs_arch $rfs_distro $image_name.dir84 85sudo chroot $image_name.dir locale-gen en_US.UTF-886 87sudo chroot $image_name.dir sed -i \88's/main/main restricted multiverse universe/g' /etc/apt/sources.list89 90sudo chroot $image_name.dir sed -i '$ a\nameserver 8.8.8.8' /etc/resolv.conf91 92sudo chroot $image_name.dir apt update93sudo chroot $image_name.dir apt -y install ssh bash-completion94sudo chroot $image_name.dir adduser --gecos "" $USER95sudo chroot $image_name.dir adduser $USER sudo96sudo umount $image_name.dir97rmdir $image_name.dir98