#!/bin/sh

set -e

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

# shellcheck disable=SC2034
usage=$(cat <<EOF
Create a SquashFS file from an image directory.

Usage:

  $ $(basename "$0") INDIR OUTDIR [ARGS ...]

ARGS are passed unchanged to mksquashfs.
${deprecated_convert}
EOF
)

parse_basic_args "$@"

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

indir=$1
outdir=$2
shift 2

# Check input directory exists
if [ ! -e "$indir" ]; then
    echo "can't squash: ${indir} does not exist" 1>&2
    exit 1
fi
# Check input directory is a directory
if [ ! -d "$indir" ]; then
    echo "can't squash: ${indir} is not a directory" 1>&2
    exit 1
fi

# Check OUTDIR exists and is a directory
if [ ! -e "$outdir" ]; then
    echo "can't squash: ${outdir} does not exist" 1>&2
    exit 1
fi
if [ ! -d "$outdir" ]; then
    echo "can't squash: ${outdir} is not a directory" 1>&2
    exit 1
fi

# Ensure mount points that ch-run needs exist. We do this by creating a
# temporary directory and appending that to an existing SquashFS archive. This
# raises mksquashfs(1)'s strange behavior w.r.t. duplicate filenames: if an
# existing file or directory "foo" is given again during append, it also goes
# into the archive, renamed to "foo_1". I was not able to find a way to get
# the behavior we want (last one given wins, merge directories).
#
# WARNING: Keep in sync with other shell scripts & Image.unpack_init().
temp=$(mktemp -d --tmpdir ch-dir2squash.XXXXXX)
# Directories. Don't follow symlinks in existence testing (issue #1015).
for i in bin dev etc mnt proc usr \
         mnt/0 mnt/1 mnt/2 mnt/3 mnt/4 mnt/5 mnt/6 mnt/7 mnt/8 /mnt/9; do
    exist_p "${indir}/${i}" || mkdir "${temp}/${i}"
done
# Files are tricky because even if the file doesn't exist, the enclosing
# directory will, triggering the bad duplicate behavior. I'm not sure what to
# do other than fail out.
for i in etc/hosts etc/resolv.conf; do
    if ( ! exist_p "${indir}/${i}" ); then
        echo "can't squash: ${indir}/${i} does not exist" 1>&2
        exit 1
    fi
done

# Create SquashFS file.
image=$(basename "${indir}")
mksquashfs "${indir}" "${outdir}/${image}.sqfs" -noappend "$@"
mksquashfs "$temp" "${outdir}/${image}.sqfs" -no-recovery

rm -rf --one-file-system "$temp"
ls -lh "${outdir}/${image}.sqfs"

deprecated_convert_warn
