qemush/bin/qemush

162 lines
3.3 KiB
Bash
Executable file

#!/bin/bash
exec_as() {
local user
user="$1"
shift
if [ "$(whoami)" != "$user" ]; then
exec sudo -u "$user" "$0" "$@"
fi
}
exec_as qemu "$@"
bin="${HOME}/launchers"
images="${HOME}/disks"
PATH="${bin}:${HOME}/bin:${PATH}"
EDITOR="${EDITOR:-nvim}"
export QEMUSH_NAME
alias ls='ls --color=auto'
alias exec='exec '
if [ -t 1 ]; then
alias pretty_cat='source-highlight --failsafe -f esc --style-file=esc.style -i'
else
alias pretty_cat=cat
fi
shopt -s expand_aliases
umask 027
perror() {
>&2 printf '\033[1;31mERROR:\033[0m \033[1m%s\033[0m\n' "$*"
}
public_help() {
local name
name="$(basename "$0")"
exec cat << EOF
${name}: usage:
${name} active - (default behaviour) list active VMs
${name} start <VM name> - start a VM
${name} watch <VM name> - attach VM screen session
${name} ls - list available VMs
${name} edit <VM name> - edit VM launching script
${name} rm <VM name> - delete launch script
${name} diskls - list available disk images
${name} diskadd <disk name> <size> - create a disk image
${name} diskrm <disk name> - delete disk image
${name} shell - start a shell as user qemu
${name} help - show this help
${name} add <path to script> [<VM name>] - add a launching script
${name} do <command> - run shell input as user qemu
${name} depcheck - check if script dependencies are met
EOF
}
error_usage() {
perror "Invalid usage"
>&2 public_help
return 1
}
public_start() {
QEMUSH_NAME="$1"
shift
exec tmux new-session \
-s "$QEMUSH_NAME" \
"$QEMUSH_NAME" \
"$@"
}
public_watch() {
[ -n "$1" ] && set -- -t "$1"
exec tmux attach "$@"
}
public_active() {
exec tmux list-sessions
}
public_ls() {
echo "Available machines:"
exec ls "$bin"
}
public_diskadd() {
QEMUSH_NAME="$1"
shift
exec qemu-img create -f qcow2 "$(pathof disk)" "$1"
}
public_diskrm() {
QEMUSH_NAME="$1"
shift
exec rm -vi -- "$(pathof disk)"
}
public_diskls() {
echo "Available disks:"
exec ls "$images"
}
public_edit() {
local file="${bin}/${1}"
"$EDITOR" "$file"
[ -f "$file" ] && exec chmod u+x "$file"
}
public_rm() {
exec rm -vi -- "${bin}/${1}"
}
public_shell() {
cd || return
exec bash -i
}
public_cat() {
pretty_cat "${bin}/${1}"
}
public_add() {
trap return EXIT
set -e
local name="${2:-$(basename "$1")}"
cp -v -i -- "$1" "${bin}/${2}"
chmod 740 "${bin}/${name}"
set +e
trap - EXIT
}
public_do() {
exec sh -c "$*"
}
bold_print() {
printf '\033['"${1}m${2}"'\033[0m: %s\n' "$3"
}
public_depcheck() {
for i in diskpath screen source-highlight ls rm cp chmod cat; do
if command -v "$i" > /dev/null; then
bold_print '1;32' OK "$i"
else
bold_print '1;31' KO "$i"
fi
done
}
function="$1"
shift
if [ -z "$function" ]; then
public_active
elif declare -F | cut -d \ -f 3- | grep '^public_' | sed 's/^public_//' | grep -q "^${function}$"; then
"public_${function}" "$@"
else
error_usage
fi