#! /bin/sh -ef

. mkve-sh-functions

show_help()
{
	cat <<EOF

mkve-pack-openvz - pack a mkve/openvz machine into a bundle

Usage: $PROG [options] <ctid> <output>

Options:
  --info=PATH      path to info;
  -q, --quiet      try to be more quiet;
  -v, --verbose    try to be more verbose;
  -V, --version    print program version and exit;
  -h, --help       show help text and exit.

EOF
	exit
}

exclude_files()
{
	for file in \
		'var/run/random-seed' \
		'etc/openssh/ssh_host_dsa_key*' \
		'etc/openssh/ssh_host_rsa_key*' \
		#
	do
		printf '%s\n' "$file"
	done
}

# parse command line
info=
ctid=
output=

TEMP=$(getopt -o ${getopt_common_opts} -n mkve-pack-openvz --long info:,${getopt_common_longopts} -- "$@")
eval set -- "${TEMP}"
while true; do
	case "$1" in
		--info)
			info="$(opt_check_read "$1" "$2")"; shift ;;
		--)
			shift; break ;;
		*)
			parse_common_option "$1" ;;
	esac
	shift
done

ctid=$(check_ctid "$1")
output=$(check_output "$2")
output_dirname="$(dirname "$output")"
output="$(basename "$output")"
workdir=$(mk_workdir "$output_dirname")

# stop container
vzctl --quiet stop "$ctid"

# now tarify container filesystem, but exclude some files
pushd /var/lib/vz/private/$ctid >/dev/null 2>&1

exclude_files >"$workdir/.exclude"
tar -cf - --numeric-owner --one-file-system -S -X "$workdir/.exclude" $(ls) \
	>"$workdir/files.tar"
rm "$workdir/.exclude"

# go to workdir
pushd "$workdir" >/dev/null 2>&1

# create info file
if [ -z "$info" ]; then
	$mkve_config set "info" 'main' 'hypervisor' 'openvz'
	$mkve_config set "info" 'main' 'arch' "$(arch)"
	$mkve_config set "info" 'image' 'image_path' 'files.tar'
else
	copycat -c main hypervisor
	copycat -c main arch
	copycat main vendor
	copycat main template
	copycat main template_version
	copycat -c image image_path
fi

# cleanup and copy openvz config file
cp /etc/vz/conf/$ctid.conf "config"
cleanup_openvz_config "config"
tar -cf "conf.tar" --remove-files "config"
$mkve_config set "info" 'openvz' 'config' 'conf.tar'

# pack
tar -cf "../$output" --dereference --remove-files $(ls -LSr)

# cleanup
popd >/dev/null 2>&1
popd >/dev/null 2>&1
rmdir "$workdir"
