#!/bin/bash
################################################################################
set -eEuo pipefail

badarg() {
    echo -n "$(basename $0): " >&2
    echo "$1" >&2
    echo "Try '$(basename $0) -h' for more information." >&2
    exit 2
}

help="Usage: $(basename $0) [-fch] [-l label] [-e options] image [container]
Create and start a container from a local image, and assign it the given name.

If second argument is omitted, defaults to assigning the container the same name
as the image.

Options:
  -f            Force overwrite if a container with the given name already exists
  -c            Configure the container with deploy options stored in the image
                metadata. By default, uses the metadata tag labeled 'config_default'
  -l [label]    Label from which to get the deploy options. Automatically sets -c
  -e [options]  Extra deploy options to assign to the container. If -e and -c are
                both used, options from image metadata and command line are combined
  -h            Display this help and exit"

# Handle options
opt_force=0
opt_config=0
opt_label='config_default'
opt_extras=''
while getopts ':fcl:e:h' arg; do
    case $arg in
        f) opt_force=1;;
        c) opt_config=1;;
        l) opt_config=1; opt_label="${OPTARG}";;
        e) opt_extras="${OPTARG}";;
        h) echo "$help"; exit 0;;
        :) badarg "Argument missing for option '-$OPTARG'";;
        ?) badarg "Invalid option '-$OPTARG'";;
    esac
done
shift $((OPTIND -1))

# Handle non-option arguments
if [[ $# -lt 1 ]]; then
    badarg "Missing image name"
else
    image="$1"
fi

if [[ $# -gt 2 ]]; then
    badarg "Too many arguments"
fi

if [[ $# -eq 2 ]]; then
    container="$2"
else
    container="$image"
fi

# Main
if [[ $opt_config -eq 1 ]]; then
    echo "Getting deploy options from image metadata label '$opt_label' ..."
    deployconf=$(podman image inspect -f "{{ .Config.Labels.${opt_label} }}" "$image")
    if [[ $deployconf == "<no value>" ]]; then
        echo "Error: could not find image metadata label '$opt_label'" >&2
        exit 1
    fi
else
    deployconf=""
fi
deployconf="$deployconf $opt_extras"

if [[ $opt_force -eq 1 ]]; then
        podman rm -i -f "$container"
fi

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