#!/bin/sh

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

# shellcheck disable=SC2034
usage=$(cat <<EOF
Unpack a Docker export tarball into a directory.

Usage:

  $ $(basename "$0") TARBALL DIR
EOF
)

parse_basic_args "$@"

if [ "$1" = --verbose ]; then
    verbose=yes
    shift
fi
if [ $# -lt 2 ]; then
    usage
fi
tarball=$1
newroot=${2}/$(basename "${tarball%.tar.gz}")

sentinel=WEIRD_AL_YANKOVIC

# Is the tarball a regular file (or symlink) and readable?
if [ ! -f "$tarball" ] || [ ! -r "$tarball" ]; then
    echo "can't read ${tarball}" 1>&2
    exit 1
fi

if [ ! -d "$newroot" ]; then
    echo "creating new image ${newroot}"
else
    if    [ -f "${newroot}/${sentinel}" ] \
       && [ -d "${newroot}/bin" ] \
       && [ -d "${newroot}/lib" ] \
       && [ -d "${newroot}/usr" ]; then
        echo "replacing existing image ${newroot}" 1>&2
        rm -Rf --one-file-system "${newroot}"
    else
        echo "${newroot} exists but does not appear to be an image" 1>&2
        exit 1
    fi
fi

mkdir "$newroot"
echo 'This directory is a Charliecloud container image.' > "${newroot}/${sentinel}"
# Use a pipe because PV ignores arguments if it's cat rather than PV.
size=$(stat -c%s "$tarball")
  pv_ -s "$size" < "$tarball" \
| gzip_ -dc \
| tar x$verbose -C "$newroot" -f - \
      --anchored --exclude='dev/*' --exclude='./dev/*'
# Make all directories writeable so we can delete image later (hello, Red Hat).
find "$newroot" -type d -a ! -perm /200 -exec chmod u+w {} +

# Ensure directories that ch-run needs exist.
mkdir -p "${newroot}/dev"
for i in $(seq 0 9); do mkdir -p "${newroot}/mnt/${i}"; done

echo "${newroot} unpacked ok"
