#!/bin/bash
#
# OCI-based mktree backend

set -e

PROGRAM=$(basename $0)
if [ "$PROGRAM" == "mktree" ]; then
    # Running from build directory
    CMAKE=yes
    NATIVE=@MKTREE_NATIVE@
    PODMAN=@PODMAN@
    CONTEXT=@CMAKE_SOURCE_DIR@
else
    # Running from source directory
    CMAKE=no
    NATIVE=no
    PODMAN=${MKTREE_ENGINE:-podman}
    CONTEXT=..
fi

if [ $NATIVE == yes ]; then
    FROM="--from @OS_NAME@:@OS_VERSION@"
else
    FROM=
fi

IMAGE=rpm
ARGS="-f Dockerfile $FROM $CONTEXT"
ROOTLESS=$([ $(id -u) == 0 ] && echo 0 || echo 1)
CMD=$1; shift

export ROOTLESS
source mktree.common

rpmtests()
{
    local opts
    local vol="$PWD:/srv:z"

    # Pass select options to $PODMAN
    case "$1" in
        # Useful for CI environments without a tty
        --interactive=*) opts=$1; shift ;;
    esac

    # Don't keep the test artifacts around in non-cmake mode
    if [ $CMAKE == no ]; then
        set -- --log "$@"
        vol=/srv
    fi

    $PODMAN run --privileged -it --rm --read-only --tmpfs /tmp -v $vol \
                --workdir /srv -e ROOTLESS=$ROOTLESS $opts $IMAGE rpmtests "$@"
}

unshared()
{
    [ $(id -u) != 0 ] && [ $NATIVE == yes ] || return 0
    $PODMAN unshare $0 $CMD "$@"
    exit
}

case $CMD in
    build) unshared
        # Build base image
        $PODMAN build --target base -t $IMAGE/base $ARGS

        # Add RPM install on top
        [ -n "$($PODMAN images -q $IMAGE)" ] && $PODMAN rmi $IMAGE
        if [ $NATIVE == yes ]; then
            # Native build
            id=$($PODMAN create $IMAGE/base)
            trap "$PODMAN rm $id >/dev/null" EXIT
            make_install $($PODMAN mount $id)
            $PODMAN commit -q $id $IMAGE
        else
            # Standalone build
            $PODMAN build --target full -t $IMAGE $ARGS
        fi
    ;;
    check)
        rpmtests "$@"
    ;;
    atshell)
        rpmtests --shell "$@"
    ;;
    shell)
        rpmtests --shell snapshot shell
    ;;
    reset)
        rpmtests --reset
    ;;
esac
