#!/bin/bash
################################################################################
# Functions/variables
quit() {
        if [[ $1 == 0 || $FLAGS_debug == $FLAGS_FALSE ]]; then
                podman rm -i -f tmp-$epoch 2>&1 > /dev/null
        fi
        exit $1
}

epoch=$(date +%s.%3N)
today=$(date +%Y-%m-%d-T%H%M)

# Handle flags
source shflags
DEFINE_boolean 'squash' false 'squash newly built layers into a single new layer' 's'
DEFINE_boolean 'debug' false "Don't delete temporary container on build fail" 'd'
DEFINE_string 'tag' 'latest' 'Tag (other than date) to assign to the image' 't'

FLAGS_HELP="Usage: $0 [-sd] [-t tag] [directory] [name]

Builds an image from the Containerfile and (optionally) Systemdfile in the
specified directory, and tags the image with the given name. If no directory
argument is given, the current working directory is used. If no name argument
is given, the image is named after the directory.
"
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

# Handle errors/arguments/cases
if [[ $# -gt 2 ]]; then
        echo "Error: too many arguments"
        echo ""
        flags_help
        exit 1
fi

if [[ -n $1 ]]; then
        directory=$1
else
        directory=$(pwd)
fi

if [[ ! -d $directory ]]; then
        echo "Error: directory \"$directory\" not found"
        echo ""
        flags_help
        exit 1
else
        cd $directory
fi

if [[ -n $2 ]]; then
        name=$2
else
        name=$(basename $(pwd))
fi

# build options
buildopts=""
if [[ $FLAGS_squash == $FLAGS_TRUE ]]; then
        buildopts="$buildopts --squash"
fi

# Main

# tell buildah to build images in docker format instead of the default OCI format
# because only docker-format images can use the SHELL directive in Containerfiles
export BUILDAH_FORMAT=docker

# build image
echo "Building image ..."
podman build -f Containerfile -t tmp-$epoch $buildopts || quit $?

# Systemdfile is for commands that need systemd to execute
if [[ -f Systemdfile ]]; then
        echo "Running build steps that require systemd ..."
        echo "Creating container ..."
        podman create --name tmp-$epoch tmp-$epoch || quit $?
        podman start tmp-$epoch || quit $?
        echo "Copying script to container ..."
        podman cp Systemdfile tmp-$epoch:/root/
        echo "Running script ..."
        podman exec tmp-$epoch bash -c "chmod +x /root/Systemdfile && /root/Systemdfile" || quit $?
        echo "Committing container to image ..."
        podman commit tmp-$epoch $name:$today || quit $?
else
        echo "Systemdfile not found, skipping container creation ..."
        # tag image we already built with appropriate tag, and untag with tmp
        podman tag tmp-$epoch $name:$today
        podman rmi tmp-$epoch
fi

# tag with latest tag
podman tag $name:$today $name:$FLAGS_tag
echo "Done!"

quit 0