#! /bin/sh -efu

. mkve-sh-functions

show_usage()
{
	cat <<EOF

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

Usage: $PROG [options] --info=<info> --image=<image> --output=<output>

Options:
  --info=PATH      path to info;
  --image=PATH     path to image;
  --output=PATH    full output path;
  --no-lzma        do not use lzma;
  -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
}

info=
image=
output=default.bun
lzma=yes

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

output=$(check_output "$output")
output_dirname="$(dirname "$output")"
output="$(basename "$output")"

#
# Create a temporary working directory into $(dirname $output).
#
workdir=$(mk_workdir "$output_dirname")
pushd "$workdir" >/dev/null 2>&1

# now create an info file into working directory
copycat -c main hypervisor
copycat -c main memory
copycat -c main arch
copycat main vendor
copycat -c image image_size
copycat -c image image_bus

# lzma
image_path="$(basename "$image")${lzma:+.lzma}"
if [ -n "$lzma" ]; then
	lzma --stdout "$image" > "$image_path"
else
	ln -s "$image" "$image_path"
fi
$mkve_config set "info" "image" "image_path" "$image_path"

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

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