#!/bin/sh

libexec="$(cd "$(dirname "$0")" && pwd)"
. "${libexec}/base.sh"

# shellcheck disable=SC2034
usage=$(cat <<EOF
Build a Charliecloud image specified by \$PWD/Dockerfile and unpack it.
Equivalent to ch-build, ch-docker2tar, ch-tar2dir sequence but somewhat less
flexible.

Usage:

  $ $(basename "$0") CONTEXT DEST [ARGS ...]

Arguments:

  CONTEXT  Docker context directory
  DEST     directory in which to place image tarball and directory
  ARGS     additional arguments passed to ch-build
EOF
)

parse_basic_args "$@"

if [ "$#" -lt 2 ]; then
    usage
fi

context=$1
dest=$2
shift 2

tag=$(basename "$PWD")

set -x

"${ch_bin}"/ch-build -t "$tag" "$context" "$@"
"${ch_bin}"/ch-docker2tar "$tag" "$dest"
"${ch_bin}"/ch-tar2dir "${dest}/${tag}.tar.gz" "$dest"
rm "${dest}/${tag}.tar.gz"
