#!/usr/bin/env bash
#
# omv-microvm-stop-cleanup — tear down the TAP device, run directory and
# jailer chroot (if any) for a microVM.
#
# Invoked as `ExecStopPost=/usr/sbin/omv-microvm-stop-cleanup %i` by the
# omv-microvm@.service systemd template unit, after firecracker has exited.
#
# Usage: omv-microvm-stop-cleanup <vm-name>

set -uo pipefail

VMNAME="${1:?usage: omv-microvm-stop-cleanup <vm-name>}"

# Must match the derivation in omv-microvm-run.
TAP_NAME="mvm-$(echo -n "$VMNAME" | md5sum | cut -c1-10)"

if ip link show "$TAP_NAME" >/dev/null 2>&1; then
    ip link del "$TAP_NAME"
fi

# The API socket file isn't removed by the kernel when Firecracker exits —
# it just becomes stale, still passing a bare `-S` check with nothing
# listening. Remove it so a stopped VM has no leftover socket to confuse.
# For a jailed VM this is a symlink into the chroot.
rm -f "/run/openmediavault-microvm/${VMNAME}/firecracker.socket" \
    "/run/openmediavault-microvm/${VMNAME}/jailed"

omv-microvm-jail-teardown "$VMNAME"

exit 0
