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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
#!/bin/sh
set -eu
ssh="ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no -i id_rsa -T"
arch=$(dpkg --print-architecture)
case $arch in
amd64)
QEMU_FLAVOR=x86_64
LINUX_FLAVOR=amd64
;;
i386)
QEMU_FLAVOR=i386
LINUX_FLAVOR=686-pae
;;
*)
echo "unknown architecture $arch"
exit 1 ;;
esac
pkgs=
# shellcheck disable=SC2016
mmdebstrap \
--mode=root \
--variant=apt \
--include="linux-image-${LINUX_FLAVOR},openssh-server,systemd-sysv,libpam-systemd,iproute2,util-linux,e2fsprogs,ifupdown,isc-dhcp-client,extlinux" \
--customize-hook='chroot "$1" passwd --delete root' \
--customize-hook='chroot "$1" useradd --home-dir /home/user --create-home user' \
--customize-hook='chroot "$1" passwd --delete user' \
--customize-hook='echo host > "$1/etc/hostname"' \
--customize-hook='echo "127.0.0.1 localhost host" > "$1/etc/hosts"' \
--customize-hook='echo "/dev/sda1 / auto errors=remount-ro 0 1" > "$1/etc/fstab"' \
trixie debian-trixie.tar
cat << END > extlinux.conf
default linux
timeout 0
label linux
kernel /vmlinuz
append initrd=/initrd.img root=/dev/sda1 net.ifnames=0 console=ttyS0
END
cat << END > interfaces
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
END
if [ ! -e ./id_rsa ] || [ ! -e ./id_rsa.pub ]; then
ssh-keygen -q -t rsa -f ./id_rsa -N ""
fi
guestfish <<EOF
sparse debian-trixie.img 1G
run
part-disk /dev/sda mbr
part-set-bootable /dev/sda 1 true
mkfs ext2 /dev/sda1
mount /dev/sda1 /
tar-in debian-trixie.tar /
copy-in id_rsa.pub /root/
mv /root/id_rsa.pub /root/.ssh/authorized_keys
chown 0 0 /root/.ssh/authorized_keys
extlinux /
copy-in extlinux.conf /
copy-file-to-device /usr/lib/EXTLINUX//mbr.bin /dev/sda
copy-in interfaces /etc/network
EOF
qemu-system-${QEMU_FLAVOR} -m 1G -net user,hostfwd=tcp::10022-:22,hostfwd=tcp::12222-:2222 \
-net nic -nographic -serial mon:stdio \
-drive file=debian-trixie.img,format=raw >qemu.log </dev/null 2>&1 &
QEMUPID=$!
trap 'cat --show-nonprinting qemu.log; kill $QEMUPID' EXIT
TIMESTAMP=$(sleepenh 0 || [ $? -eq 1 ])
TIMEOUT=5
NUM_TRIES=40
i=0
while true; do
rv=0
$ssh -p 10022 -o ConnectTimeout=$TIMEOUT root@localhost echo success || rv=1
[ $rv -eq 0 ] && break
# if the command before took less than $TIMEOUT seconds, wait the remaining time
TIMESTAMP=$(sleepenh "$TIMESTAMP" $TIMEOUT || [ $? -eq 1 ]);
i=$((i+1))
if [ $i -ge $NUM_TRIES ]; then
break
fi
done
if [ $i -eq $NUM_TRIES ]; then
echo "timeout reached: unable to connect to qemu via ssh"
exit 1
fi
$ssh -p 10022 root@localhost systemctl poweroff
wait $QEMUPID
trap - EXIT
rm debian-trixie.img debian-trixie.tar extlinux.conf id_rsa id_rsa.pub interfaces qemu.log
exit 0
|