#!/bin/sh

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

# shellcheck disable=SC2034
usage=$(cat <<EOF
Flatten a builder image into a Charliecloud SquashFS file.

Usage:

  $ $(basename "$0") [-b BUILDER] IMAGE OUTDIR [ARGS ...]

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

parse_basic_args "$@"

# Kludgey argument parsing.
while true; do
    case $1 in
        -b|--builder)
            shift
            CH_BUILDER=$1
            shift
            ;;
        *)
            break
            ;;
        esac
done

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

builder_choose

image=$1
outdir=$2
shift 2

if [ ! -d "$outdir" ]; then
    echo "${outdir} is not a directory" 1>&2
    exit 1
fi

# mktemp is used for intermediate files to avoid heavy metadata loads on
# certain filesystems
temp=$(mktemp -d --tmpdir ch-builder2squash.XXXXXX)
# Get image as a directory
"${ch_bin}/ch-builder2tar" -b "$CH_BUILDER" --nocompress "$image" "$temp"
image=$(tag_to_path "$image")
tar=${temp}/${image}.tar
"${ch_bin}/ch-tar2dir" "${tar}" "$temp"
# Create squashfs, and clean up intermediate files and folders.
"${ch_bin}/ch-dir2squash" "${temp}/${image}" "$outdir" "$@"
rm -rf --one-file-system "$temp"
