#!/bin/bash
################################################################################
# Handle flags
source shflags
DEFINE_boolean 'overwrite' false 'Overwrite container if one with same name already exists.' 'o'
DEFINE_boolean 'config' false 'Automatically configure container with deploy options stored in image metadata.' 'c'
DEFINE_string 'label' 'deployopts' 'Image metadata label from which to get the deploy options.' 'l'

FLAGS_HELP="Usage: $0 [-oc] [-d label] [image] [name]

Creates and starts a container from the specified image, and assigns it the
specified name. If no image argument is given, uses the current working
directory as the name of the image. If no name argument is given, the container
is given the same name as the image.
"
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
        image=$1
else
        echo "Warning: No image name given. Assuming image name from current working directory."
	image=$(basename $(pwd))
fi

if [[ -n $2 ]]; then
        name=$2
else
        name=$image
fi

if [[ $FLAGS_config == $FLAGS_TRUE ]]; then
        echo "Getting deploy options from image metadata label \"$FLAGS_label\" ..."
        deployopts=$(podman image inspect -f "{{ .Config.Labels.${FLAGS_label} }}" $image)
        if [[ $deployopts == "<no value>" ]]; then
                echo "Error: image metadata label \"$FLAGS_label\" is empty or nonexistent."
                exit 2
        fi
else
        deployopts=""
fi

if [[ $FLAGS_overwrite ]]; then
        podman rm -i -f $name
fi

podman run -itd --name $name --hostname $name $deployopts $image
echo "Done!"