#!/usr/local/bin/cbsd
#v12.0.4
CBSDMODULE="bhyve"
MYARG="jname"
MYDESC="Force to cleanup bhyve 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 bcleanup jname=myvm1

"

# Cleanup all items of broken jail
. ${subrdir}/nc.subr
. ${cbsdinit}

. ${system}
. ${mdtools}
. ${subrdir}/vnet.subr

. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && err 1 "${N1_COLOR}No such domain: ${N2_COLOR}${jname}${N0_COLOR}"
[ "${emulator}" != "bhyve" ] && err 1 "${N1_COLOR}Not bhyve 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 ${CBSD_APP}: bcleanup: destroy tap for ${jname}: ${i}
			${IFCONFIG_CMD} ${i} >/dev/null 2>&1 && ${IFCONFIG_CMD} ${i} destroy
			# clean ARP ( no needed when destroy iface ? )
			# arp -d -i ${i}
			#cbsdsqlro ${jailsysdir}/${jname}/local.sqlite "SELECT nic_hwaddr FROM bhyvenic" | while read nic_hwaddr; do
			#	[ "${nic_hwaddr}" = "0" ] && continue
			#	#/usr/sbin/arp -dn ${nic_hwaddr} > /dev/null 2>&1
		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

exit 0
