#!/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".
${deprecated_convert}
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

# If no tag given, we don't know what to tar and things get exciting.
if [[ -z $tag ]]; then
    echo 'error: must specify -t' 1>&2
    exit 1
fi

tag_fs=$(tag_to_path "$tag")

set -x

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

deprecated_convert_warn
