VMs/lib.sh

76 lines
1.7 KiB
Bash

#!/bin/bash -e
DIR="$(dirname "${BASH_SOURCE[0]}")"
BRIDGE=virbr0
NORMAL=$'\e[0m'
BOLD=$'\e[1m'
RED=$'\e[31m'
function ask_yn() {
local ans
printf '%s (Y/n) ' "$1" >&2
read -r ans
case "${ans,,}" in
y*|'') return 0 ;;
*) return 1 ;;
esac
}
declare -A ISO
declare -a OPTS
function download_isos() {
for iso in "${!ISO[@]}"; do
if ! [ -f "$iso" ] && ask_yn "download $iso?"; then
curl -LC- -o "$iso" "${ISO[$iso]}"
fi
if [ -f "$iso" ]; then
OPTS+=(-drive "file=$iso,media=cdrom,readonly=on")
fi
done
}
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 \
"${OPTS[@]}" \
"$@"
)
}