#!/usr/local/bin/cbsd
#v11.1.6
globalconf="${distdir}/cbsd.conf";
CBSDMODULE="jail"
MYARG="jname"
MYOPTARG="sharedfs"
MYDESC="Force unmount and cleanup for offline jail"

# Cleanup all items of broken jail
. ${subrdir}/nc.subr
. ${system}
. ${mdtools}
. ${strings}

sharedfs=0

. ${cbsdinit}

. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && return 0 #only for registered jails

# remove zombie jail
if [ "${jid}" != "0" ]; then
	if [ "${platform}" != "DragonFly" ]; then
		${JAIL_CMD} -r ${jid}
	fi
	 ${miscdir}/sqlcli ${dbdir}/local.sqlite "UPDATE jails SET jid=\"0\" WHERE jname=\"${jname}\""
fi

[ "${mdsize}" != "0" ] && MDFILE=$( eval find_md_by_mountpath ${data} )
[ ${baserw} -eq 1 ] && path=${data}

rootflags=

if [ ${baserw} -eq 1 ]; then
	#test for zfs mounted in baserw=1
	case ${zfsfeat} in
		1)
			. ${subrdir}/zfs.subr
			zfsmnt ${data}
			if [ $? -eq 1 ]; then
				# dont remove ~cbsd/jails-data/$jname-data
				rootflags="no_unmount_root"
			fi
		;;
	esac
fi

if [ ${baserw} -eq 1 ]; then
	umount_cdirs ${data} ${rootflags}
else
	umount_cdirs ${path} ${rootflags}
fi

[ "${mdsize}" != "0" -a -n "${MDFILE}" ] && unmountmd md=${MDFILE}

jaillock="${jailsysdir}/${jname}/locked"
if [ ${sharedfs} -eq 0 ]; then
	[ -f "${jaillock}" ] && ${RM_CMD} -f ${jaillock}
fi

# vnet cleanup
if [ "${vnet}" = "1" ]; then
	# for vnet we can make another action
	. ${subrdir}/vnet.subr

	for i in $( ${SEQ_CMD} 0 16 ); do
		myepair=
		myepair=$( get_my_device epair ${jname}-eth${i} )
		[ -z "${myepair}" ] && continue
		${IFCONFIG_CMD} ${myepair} >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			${ECHO} "${N1_COLOR}jcleanup: destroy epair for ${jname}: ${N2_COLOR}${myepair}${N0_COLOR}"
			${IFCONFIG_CMD} ${myepair} destroy
		fi
	done
fi

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