#!/usr/bin/env cbsd
#v11.2.0
CIXARG="jname mode"
CIXOPTARG="name"
CIXDESC="xen checkpoint"
CBSDMODULE="xen"
ADDHELP="mode=create,list,destroyall\n\
  create   - create new checkpoint\n\
  list     - show available checkpoint for current domain\n\
  destroyall - destroy all checkpoints for current domain\n\
name= name of checkpoint. by default: checkpoint\n"

. ${subrdir}/nc.subr

name="checkpoint"

cixinit

# store original name before rcconf init
oname="${name}"

. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && err 1 "${N1_COLOR}No such domains: ${N2_COLOR}${jname}${N0_COLOR}"
[ "${emulator}" != "xen" ] && log_err 1 "${N1_COLOR}Not in xen mode${N0_COLOR}"

# restore original name
name="${oname}"

CHECKPOINT_DIR="${jailsysdir}/${jname}/checkpoints"
[ ! -d "${CHECKPOINT_DIR}" ] && ${MKDIR_CMD} -p "${CHECKPOINT_DIR}"

checkpoint_create()
{
	[ "${jid}" -eq 0 ] && log_err 1 "Not running"
	[ -z "${name}" ] && log_err 1 "${N1_COLOR}Empty checkpoint name${N0_COLOR}"

	CHECKPOINT="${CHECKPOINT_DIR}/${name}.ckp"

	# todo: check for .ckp extenions

	if [ -r "${CHECKPOINT}" ]; then
		${ECHO} "${N1_COLOR}Prune old checkpoint...${N0_COLOR}"
		cbsdlogger NOTICE ${CIX_APP}: prune old checkpoint: ${CHECKPOINT}
		${RM_CMD} -f "${CHECKPOINT}" "${CHECKPOINT}.kern" "${CHECKPOINT}.meta"
	fi

	/usr/local/sbin/xl save ${jname} "${CHECKPOINT}"
	${SYNC_CMD}
	cbsdlogger NOTICE ${CIX_APP}: checkpoint created: ${CHECKPOINT}
	# todo: rewrite to file modification test
	i=1
	while [ ${i} -le 5 ]; do
		${ECHO} "${N1_COLOR}Waiting and sure that the info is written on the disk: ${N2_COLOR}${i}/5${N0_COLOR}"
		sleep 1
		i=$((i + 1))
	done

	${SYNC_CMD}
	${ECHO} "${N1_COLOR}Checkpoint was created!: ${N2_COLOR}${CHECKPOINT}${N0_COLOR}"
	return 0
}

checkpoint_list()
{
	${ECHO} "${N1_COLOR}Created checkpoint for ${N2_COLOR}${jname}${N1_COLOR}:${N0_COLOR}"
	${FIND_CMD} "${CHECKPOINT_DIR}/" -mindepth 1 -maxdepth 1 -name \*.ckp -type f -exec ${BASENAME_CMD} {} \; | ${SORT_CMD} | while read _file; do
		local _p1=${_file%%.*}
		${ECHO} "${_p1}"
	done
}

case "${mode}" in
	create)
		checkpoint_create
		;;
	destroyall)
		[ -d "${CHECKPOINT_DIR}" ] && ${RM_CMD} -rf "${CHECKPOINT_DIR}"
		;;
	list)
		checkpoint_list
		;;
	*)
		err 1 "${N1_COLOR}Unknown mode: ${N2_COLOR}${mode}${N0_COLOR}"
esac

exit $?
