#!/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 'deployopts' 'deployopts' 'Image metadata label from which to get the deploy options.' 'd'
FLAGS_HELP="Usage: $0 [-o] [-d label] image [name]

Creates and starts a container from the specified image. If a second
argument is given, the container name is set to that string. Otherwise, the
container is given the same name as the image.
"
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

if [[ -n $1 ]]; then
        image=$1
else
        echo "Error: need image name"
        echo ""
        flags_help
        exit 1
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_deployopts\" ..."
        deployopts=$(podman image inspect -f "{{ .Config.Labels.${FLAGS_deployopts} }}" $image)
        if [[ $deployopts == "<no value>" ]]; then
                echo "Error: image metadata label \"$FLAGS_deployopts\" is empty or nonexistent."
                exit 2
        fi
else
        deployopts=""
fi

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

podman create --name $name $deployopts $image
podman start $name
echo "Done!"