#!/bin/bash

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

# shellcheck disable=SC2034
usage=$(cat <<EOF
Build a Charliecloud image from Dockerfile and unpack it into a directory.

Usage:

  $ $(basename "$0") -t TAG [ARGS ...] CONTEXT OUTDIR

ARGS are passed unchanged to "ch-build".
EOF
)

parse_basic_args "$@"

[[ $# -gt 3 ]] || usage

# Strip off last argument, so we can pass the rest to ch-build. Note this is
# essentially impossible to do robustly in POSIX sh.
args=("${@:1:$#-1}") # all but last arg
outdir="${*: -1}"    # last arg
# Parse -t, because we need TAG in this script.
while [[ $# -gt 0 ]]; do
    opt=$1; shift
    case $opt in
       --tag|-t)
            tag=$1
            ;;
    esac
done

set -x

"${ch_bin}"/ch-build "${args[@]}"
"${ch_bin}"/ch-builder2tar "$tag" "$outdir"
"${ch_bin}"/ch-tar2dir "${outdir}/${tag}.tar.gz" "$outdir"
rm "${outdir}/${tag}.tar.gz"
