#!/usr/local/bin/cbsd
#v11.1.17
globalconf="${workdir}/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"

. ${subr}
. ${tools}
init $*

. ${system}

[ -z "${cbsd_queue_name}" ] && cbsd_queue_name="/clonos/imported/"

[ -z "${jname}" -a -z "${img}" ] && err 1 "${MAGENTA}Please specify ${GREEN}jname=${MAGENTA} or ${GREEN}img=${NORMAL}"

dirpath=$( /bin/realpath ${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 "${MAGENTA}no such ${GREEN}${imgpath}${NORMAL}"

# CBSD QUEUE
if [ -x "${moduledir}/cbsd_queue.d/cbsd_queue" ]; then
	[ "${cbsd_queue_name}" != "none" ] && cbsd_queue cbsd_queue_name=${cbsd_queue_name} id=${fname} cmd=imgremove status=1
fi

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

ret=$?

/bin/rm -f hdr.$$

if [ ${ret} -ne 0 ]; then
	# CBSD QUEUE
	if [ -x "${moduledir}/cbsd_queue.d/cbsd_queue" ]; then
		[ "${cbsd_queue_name}" != "none" ] && cbsd_queue cbsd_queue_name=${cbsd_queue_name} id=${fname} cmd=imgremove status=2
	fi
	err 1 "${MAGENTA}Unable to get header: ${GREEN}${imgpath}${MAGENTA}. Not CBSD image?${NORMAL}"
fi

/bin/rm -f ${imgpath}

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

# CBSD QUEUE
if [ -x "${moduledir}/cbsd_queue.d/cbsd_queue" ]; then
	[ "${cbsd_queue_name}" != "none" ] && cbsd_queue cbsd_queue_name=${cbsd_queue_name} id=${fname} cmd=imgremove status=2
fi

exit 0
