VMs/lib.sh

74 lines
1.6 KiB
Bash

#!/bin/bash -eu
DIR="$(dirname "${BASH_SOURCE[0]}")"
BRIDGE=virbr0
NORMAL=$'\e[0m'
BOLD=$'\e[1m'
RED=$'\e[31m'
ask_yn() {
local a
read -rp "$* (Y/n) " a
[ -z "$a" ] || [[ "${a,,}" == y* ]]
}
declare -A ISO
declare -a OPTS
download_isos() {
local curl file
curl=(curl -ZLC-)
for iso in "${!ISO[@]}"; do
file="$iso.iso"
curl+=(-o "$file" "${ISO[$iso]}")
OPTS+=(-drive "file=$file,media=cdrom,readonly=on")
done
"${curl[@]}"
}
_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"
}
_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"
}
qemu() {
local ram=2G
local maxram; maxram="$(_getmaxram)"
local net; net="$(_getnet)"
(set -x
qemu-system-x86_64 -accel kvm \
-monitor stdio \
-M q35 \
-bios /usr/share/edk2/x64/OVMF.4m.fd \
-cpu host \
-m "$ram,maxmem=$maxram" \
-vga virtio \
-audio pipewire,model=hda \
-drive if=virtio,file=hda.qcow2 \
-nic "model=virtio-net-pci,type=$net" \
-device qemu-xhci \
-object "memory-backend-ram,id=mem,size=$ram,share=on" \
-numa node,memdev=mem \
"${OPTS[@]}" \
"$@"
)
}