#!/bin/sh

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

usage () {
    cat 1>&2 <<EOF
Unpack a Docker export tarball into a directory.

Usage:

  $ $(basename $0) TARBALL DIR

Extract the tarball, which must be a Linux filesystem image e.g. from
ch-docker2tar, into a subdirectory of DIR named as the tarball with .tar.gz
removed. For example, if the tarball is foo.tar.gz, unpack into DIR/foo.

If the subdirectory doesn't exist, it is created. If it does exist and appears
to be a Charliecloud container image, it is removed and replaced. Otherwise,
the script aborts with an error.

Warning:

  Do not place DIR on a shared filesystem (e.g., your home directory, project
  space, scratch) unless specifically instructed by your site admins. Doing so
  may cause excess metadata load on the filesystem, resulting in poor
  performance for you and everyone else trying to do work at the same time.

EOF
    exit ${1:-1}
}

set -e

if [ "$1" = --help ]; then
    usage 0
fi
if [ "$1" = --version ]; then
    version
    exit 0
fi
if [ "$1" = --verbose ]; then
    VERBOSE=v
    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" -o ! -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"
tar x$VERBOSE -I $GZIP_CMD -C "$NEWROOT" -f "$TARBALL" --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"
