#!/bin/sh
#  Copyright (c) 2013-2017, Parallels International GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#  Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
#  Schaffhausen, Switzerland.
#
# Parameters are passed in environment variables.
# Required parameters:
#   STATUSFD	  - file descriptor for sending signal to vzctl
#   WAITFD	  - file descriptor for receiving signal from vzctl
#   CRTOOLS_SCRIPT_ACTION - current action (set by criu)

exec 1>&2

if [ -z "$CRTOOLS_SCRIPT_ACTION" ]; then
	echo "Missing parameter CRTOOLS_SCRIPT_ACTION"
	exit 1
fi

set -e
case "$CRTOOLS_SCRIPT_ACTION" in
"pre-dump")
	if [ -z "$CRTOOLS_IMAGE_DIR" ]; then
		echo "Missing parameter CRTOOLS_IMAGE_DIR"
		exit 1
	fi
	if [ -n "$VEID" ]; then
		cat /sys/fs/cgroup/memory/machine.slice/$VEID/memory.limit_in_bytes > \
			$CRTOOLS_IMAGE_DIR/vz_memory_limit_in_bytes.img || \
			{ echo "Failed to dump memory limit in bytes"; exit 1; }
		cat /sys/fs/cgroup/memory/machine.slice/$VEID/memory.memsw.limit_in_bytes > \
			$CRTOOLS_IMAGE_DIR/vz_memory_memsw_limit_in_bytes.img || \
			{ echo "Failed to dump memory swap limit in bytes"; exit 1; }
	fi
	;;
"post-dump")
	if [ -z "$CRTOOLS_IMAGE_DIR" ]; then
		echo "Missing parameter CRTOOLS_IMAGE_DIR"
		exit 1
	fi
	if [ -n "$VEID" ]; then
		cgexec -g ve:$VEID cat /proc/sys/kernel/core_pattern > \
			$CRTOOLS_IMAGE_DIR/vz_core_pattern.img || { echo "Failed to dump core_pattern"; exit 1; }
		cgexec -g ve:$VEID cat /proc/sys/fs/fsync-enable > \
			$CRTOOLS_IMAGE_DIR/vz_fsync-enable.img || { echo "Failed to dump fsync-enable"; exit 1; }
		cgexec -g ve:$VEID cat /proc/sys/fs/odirect_enable > \
			$CRTOOLS_IMAGE_DIR/vz_odirect_enable.img || { echo "Failed to dump odirect_enable"; exit 1; }
		cgexec -g ve:$VEID cat /proc/sys/kernel/randomize_va_space > \
			$CRTOOLS_IMAGE_DIR/vz_randomize_va_space.img || { echo "Failed to dump randomize_va_space"; exit 1; }
	fi
	ret=0
	[ -n "$STATUSFD" ] && printf '\0\0\0\0' >&${STATUSFD}
	[ -n "$WAITFD" ] && ret=$(head -c 4 <&$WAITFD | hexdump -e '"%d"' -n 4)

	[ "$ret" = "0" ]
	;;
esac
exit 0
