#!/bin/sh

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

# shellcheck disable=SC2034
usage=$(cat <<EOF
Flatten a Docker image into a Charliecloud image tarball.

Usage:

  $ $(basename "$0") IMAGE OUTDIR

You must have sufficient privilege (via sudo) to run the Docker commands.
EOF
)

parse_basic_args "$@"

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

image=$1
outdir=$2
tar="$outdir"/$(echo "$image" | sed 's/\//./g').tar.gz

cid=$(docker_ create --read-only "$image")
size=$(docker_ image inspect "$image" --format='{{.Size}}')
#docker_ ps -af "id=$cid"
docker_ export "$cid" | pv_ -s "$size" | gzip_ -6 > "$tar"
docker_ rm "$cid" > /dev/null
ls -lh "$tar"
