#!/bin/sh
#
# Perform a bind mount, copying existing files as we do so to ensure the
# overlaid path has the necessary content.
# If the target is a directory and overlayfs is available (and the environment
# variable MOUNT_COPYBIND_AVOID_OVERLAYFS=1 is not set), then an overlay mount
# will be attempted first.

if [ $# -lt 2 ]; then
    echo >&2 "Usage: $0 spec mountpoint [OPTIONS]"
    exit 1
fi

# e.g. /var/volatile/lib
spec=$1

# e.g. /var/lib
mountpoint=$2

if [ $# -gt 2 ]; then
    options=$3
else
    options=
fi

[ -n "$options" ] && options=",$options"

mkdir -p "${spec%/*}"

if [ -d "$mountpoint" ]; then

    if [ -d "$spec" ]; then
        specdir_existed=yes
    else
        specdir_existed=no
        mkdir "$spec"
        # If the $spec directory is created we need to take care that
        # the selinux context is correct
        if command -v selinuxenabled > /dev/null 2>&1; then
            if selinuxenabled; then
                restorecon "$spec"
            fi
        fi
    fi

    # Fast version of calculating `dirname ${spec}`/.`basename ${spec}`-work
    overlay_workdir="${spec%/*}/.${spec##*/}-work"
    if [ "$MOUNT_COPYBIND_AVOID_OVERLAYFS" != 1 ]; then
        mkdir "${overlay_workdir}"
    fi

    # Try to mount using overlay, which is much faster than copying files.
    # If that fails, fall back to slower copy.
    if command -v selinuxenabled > /dev/null 2>&1; then
        if selinuxenabled; then
            mountcontext=",rootcontext=$(matchpathcon -n "$mountpoint")"
        fi
    fi
    if [ "$MOUNT_COPYBIND_AVOID_OVERLAYFS" = 1 ] || ! mount -t overlay overlay -olowerdir="$mountpoint",upperdir="$spec",workdir="$overlay_workdir""$mountcontext" "$mountpoint" > /dev/null 2>&1; then
        rm -rf "$overlay_workdir"

        if [ "$specdir_existed" != "yes" ]; then
            cp -aPR "$mountpoint"/. "$spec/"
        fi

        mount -o "bind$options" "$spec" "$mountpoint"
        # restore the selinux context.
        if command -v selinuxenabled > /dev/null 2>&1; then
            if selinuxenabled; then
                restorecon -R "$mountpoint"
            fi
        fi
    fi
elif [ -f "$mountpoint" ]; then
    if [ ! -f "$spec" ]; then
        cp -aP "$mountpoint" "$spec"
    fi

    mount -o "bind$options" "$spec" "$mountpoint"
    # restore the selinux context.
    if command -v selinuxenabled > /dev/null 2>&1; then
        if selinuxenabled; then
            restorecon -R "$mountpoint"
        fi
    fi
fi
