#!/usr/local/bin/cbsd
#v11.1.17
globalconf="${distdir}/cbsd.conf";
MYARG="path"
MYOPTARG="jname img"
MYDESC="Remove CBSD image from directory"
ADDHELP="jname= image name without .img postfix\n\
img= basename of file (with postfix, e.g: jail1.img\n"
CBSDMODULE="sys"

. ${subrdir}/nc.subr

. ${cbsdinit}

. ${system}

[ -z "${jname}" -a -z "${img}" ] && err 1 "${N1_COLOR}Please specify ${N2_COLOR}jname=${N1_COLOR} or ${N2_COLOR}img=${N0_COLOR}"

dirpath=$( ${REALPATH_CMD} ${path} )

## todo: check for safe dir list ( export, import, jail_imported )

if [ -n "${jname}" ]; then
	fname="${jname}.img"
else
	fname="${img}"
fi

imgpath="${dirpath}/${fname}"

[ ! -r "${imgpath}" ] && err 1 "${N1_COLOR}no such ${N2_COLOR}${imgpath}${N0_COLOR}"

# CBSD QUEUE
if [ "${mod_cbsd_queue_enabled}" = "YES" -a -z "${MOD_CBSD_QUEUE_DISABLED}" ]; then
	[ -n "${cbsd_imgremove_queue_name}" ] && ${cbsd_queue_backend} cbsd_queue_name=${cbsd_imgremove_queue_name} id=${fname} cmd=imgremove status=1
fi

imgpart out=${tmpdir}/hdr.$$ jname=${imgpath} part=header mode=extract

ret=$?

/bin/rm -f hdr.$$

if [ ${ret} -ne 0 ]; then
	# CBSD QUEUE
	if [ "${mod_cbsd_queue_enabled}" = "YES" -a -z "${MOD_CBSD_QUEUE_DISABLED}" ]; then
		[ -n "${cbsd_imgremove_queue_name}" ] && ${cbsd_queue_backend} cbsd_queue_name=${cbsd_imgremove_queue_name} id=${fname} cmd=imgremove status=2
	fi
	err 1 "${N1_COLOR}Unable to get header: ${N2_COLOR}${imgpath}${N1_COLOR}. Not CBSD image?${N0_COLOR}"
fi

/bin/rm -f ${imgpath}

[ -f ${imgpath}.size ] && /bin/rm -f ${imgpath}.size
[ -f ${imgpath}.md5 ] && /bin/rm -f ${imgpath}.md5

# CBSD QUEUE
if [ "${mod_cbsd_queue_enabled}" = "YES" -a -z "${MOD_CBSD_QUEUE_DISABLED}" ]; then
	[ -n "${cbsd_imgremove_queue_name}" ] && ${cbsd_queue_backend} cbsd_queue_name=${cbsd_imgremove_queue_name} id=${fname} cmd=imgremove status=2
fi

exit 0
