#!/bin/bash

# Build image from the official rust image on a very
# conservative base image (operating system wize):

thisfile=$(basename $0)

# Be defensive
set -u          # If you try to access an undefined variable, that is an error.

set -o pipefail # If any command in a pipeline returns a non-zero exit code,
                # the return code of the entire pipeline is the exit code of
                # the last failed command.

err () {
    msg="$1"
    echo "Error: $1" >&2
    exit 1
}

usage () {
    echo "Usage:"
    echo "  $thisfile destinationfolder"
}

[ $# -ne 1 ] && err "Required destination folder argument missing"
if [ "$1" == '-h' ] || [ "$1" == '--help' ]; then
    usage
fi

export destination="$1"
[ -d "$destination" ] || err "Destination $destination does not exist"
which podman > /dev/null 2>&1 || err "Podman needs to be installed"

img=$(podman build --quiet ..)
if [ $? == 0 ]; then
    image_built=yes
else
    image_built=no
fi
echo "image_built: $image_built"
echo "img: $img"
if [ "$image_built" == no ]; then
    if [ -n "$img" ] && [ -f "$img" ]; then
        rm -f "$img"
    fi
    echo "Failed to build image; exiting" >&2
    exit 1
fi

# Start a container from the image:
export cid=$(podman run -d $img sleep infinity) && \
  podman unshare ../packaging/_copy_artefacts_from_container.sh && \
  podman kill $cid > /dev/null
[ "$image_built" == yes ] && podman image rm --force "$img"
