#!/usr/bin/env cbsd
#v12.0.5
CBSDMODULE="qemu"
CIXARG="jname"
MYDESC="Force to cleanup Qemu VM-related stuff, e.g. nics"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 After launching and stopping (crash) of the virtual machine in the host system, some VM-specific
settings may remain in runtime, which are no longer needed. This script finds these settings and
deletes. For example, destroys pseudo network card interfaces of a virtual machine, remove
traffic counter and so on...

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}jname=${N0_COLOR} - target VM;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd qcleanup jname=myvm1

${H3_COLOR}See also${N0_COLOR}:

 cbsd bstart --help
 cbsd bstop --help

"

. ${subrdir}/nc.subr
. ${system}
. ${mdtools}
. ${subrdir}/vnet.subr
. ${subrdir}/rcconf.subr
cixinit

[ "${emulator}" != "qemu" ] && err 1 "${N1_COLOR}Not qemu mode${N0_COLOR}"
[ ${jid} -ne 0 ] && err 1 "${N1_COLOR}domain ${jname} is running, pid: ${N2_COLOR}${jid}${N0_COLOR}"

# cleanup for tap ifaces, max nic=16
nic_num=16

while [ ${nic_num} -ne -1 ]; do
	if mytap=$( get_nic_by_descr ${jname}-nic${nic_num} ); then
		for i in ${mytap}; do
			cbsdlogger NOTICE ${CIX_APP}: bcleanup: destroy tap for ${jname}: ${i}
			case "${platform}" in
				Linux)
					${IP_CMD} link delete ${i}
					[ -r "${workdir}/tmp/nic-${i}.desc" ] && ${RM_CMD} -f "${workdir}/tmp/nic-${i}.desc"
					;;
				*)
					${IFCONFIG_CMD} ${i} >/dev/null 2>&1 && ${IFCONFIG_CMD} ${i} destroy
					;;
			esac
		done
	fi
	nic_num=$(( nic_num - 1 ))
done

# delete orphaned vale_ports if exists
cbsdsqlrw local "DELETE FROM vale_ports WHERE jname='${jname}'"

# cleanup ipfw counter
fwcounters jname=${jname} mode=remove

# monitor socket
[ -S ${jailsysdir}/${jname}/qemu-monitor.sock ] && ${RM_CMD} -f ${jailsysdir}/${jname}/qemu-monitor.sock

exit 0
