lxc-ramdisk/bin/mkvm.sh

111 lines
1.9 KiB
Bash
Executable File

#! /usr/bin/env bash
KEEP=0
SYSDIR="/ramdisk/sys"
TMPDIR="/ramdisk/tmp"
help() {
echo "testvm.sh DISTRO [CMD] [ARGS]"
echo " -k|--keep: Don't destroy the VM after running"
echo " --copy PATHSRC PATHDEST: copy PATHSRC into the container as PATHDEST"
}
if [ $# -lt 2 ]; then
help
exit 0
fi
# Files to copy into container
COPY=()
COPYDEST=()
while true; do
case "$1" in
"-h"|"--help")
help
exit 0
;;
"-k"|"--keep")
KEEP=1
shift
;;
"--copy")
shift
PATHSRC="$1"
if [ ! -e "$PATHSRC" ]; then
echo "COPY ERROR: File/Folder "$PATHSRC" does not exist."
exit 1
fi
shift
PATHDEST="$1"
COPY+=("$PATHSRC")
COPYDEST+=("$PATHDEST")
shift
;;
*)
# Optional args processing finished
# If no first argument is passed, syntax error
if [[ "$1" = "" ]]; then
help
exit 1
fi
TYPE="$1"
shift
break
;;
esac
done
TEMPLATE=/var/lib/lxc/"$TYPE".template
if [ ! -f "$TEMPLATE" ]; then
echo "ERROR: No such VM type "$TYPE""
exit 1
fi
export VMNAME="$TYPE-$RANDOM"
echo "$VMNAME"
export LXCROOTFS="overlayfs:/ramdisk/sys/$TYPE:/ramdisk/tmp/$VMNAME"
echo "$LXCROOTFS"
LXCDIR=/var/lib/lxc/"$VMNAME"
mkdir "$LXCDIR"
envsubst < "$TEMPLATE" > "$LXCDIR"/config
ROOTFS="$TMPDIR"/"$VMNAME"
mkdir -p "$ROOTFS"/etc/
echo "$VMNAME" > "$ROOTFS"/etc/hostname
# Copy files into the VM
for fileIndex in ${!COPY[@]}; do
PATHSRC="${COPY[$fileIndex]}"
PATHDEST="$ROOTFS""${COPYDEST[$fileIndex]}"
# Create parent dirs
#DESTPATH="$(realpath "$file")"
#DESTPATH="$ROOTFS""$DESTPATH"
PARENTPATHDEST="$(dirname "$PATHDEST")"
mkdir -p "$PARENTPATHDEST"
cp --dereference -r "$PATHSRC" "$PATHDEST"
done
CMD="$1"
shift
if [[ "$CMD" != "" ]]; then
lxc-start -n "$VMNAME"
lxc-attach -n "$VMNAME" -- "$CMD" "$@"
if [ $KEEP -eq 0 ]; then
lxc-stop --kill "$VMNAME"
lxc-destroy -n "$VMNAME"
fi
else
lxc-start -n "$VMNAME"
lxc-attach -n "$VMNAME" bash
if [ $KEEP -eq 0 ]; then
lxc-stop --kill "$VMNAME"
lxc-destroy -n "$VMNAME"
fi
fi