VMs/lib.sh

58 lines
1.3 KiB
Bash

#!/bin/bash -e
DIR="$(dirname "${BASH_SOURCE[0]}")"
BRIDGE=virbr0
function ask_yn() {
local ans
printf '%s (Y/n) ' "$1" >&2
read -r ans
case "${ans,,}" in
y*|'') return 0 ;;
*) return 1 ;;
esac
}
function _getmaxram() {
local ram; ram="$(free -g | awk '/^Mem:/{print $2 - 2}')"
if [ "$ram" -le 2 ]; then ram=2
elif [ "$ram" -gt 32 ]; then ram=32; fi
echo "${ram}G"
}
function _getnet() {
local net=user
if ! ip link show "$BRIDGE" | grep -q UP; then
ask_yn 'create bridge?' && sudo "$DIR/startnat.sh" "$BRIDGE" > /dev/null
fi
if ip link show "$BRIDGE" | grep -q UP; then
net="bridge,br=$BRIDGE"
fi
echo "$net"
}
# TODO: -bios /usr/share/OVMF/OVMF_CODE.fd
function qemu() {
local maxram; maxram="$(_getmaxram)"
local net; net="$(_getnet)"
(set -x
qemu-system-x86_64 -accel kvm \
-M q35 \
-bios /usr/share/ovmf/x64/OVMF.fd \
-cpu host \
-m "2G,maxmem=$maxram" \
-vga virtio \
-drive if=virtio,file=hda.qcow2 \
-audio pipewire,model=hda \
-nic "model=virtio-net-pci,type=$net" \
-device qemu-xhci \
-object memory-backend-ram,id=mem,size=2G,share=on \
-numa node,memdev=mem \
"$@"
)
}