#!/bin/sh
# Create a monitored container service

pmargs=""
enable=
dryrun=
name=

usage()
{
    cat <<EOF
summary:
  Create a supervised Finit service for a podman container.

  Use '-e' flag to also enable the service.  When called at bootstrap,
  this ensures Finit starts the new service when changing runlevel.

  Please note, either the entry point or the CMD must run in foreground.

usage:
  podman-service [opts] IMAGE [CMD [ARG]]

options:
  -d "DESCRIPTION"  Optional service description, default: "NAME container"
  -e                Enable service (does not reload Finit)
  -h                Show this help text
  -n NAME           Short name, lower-case, no spaces, e.g., 'nginx'
  -p "ARGS"         Arguments for podman, example: '-p "-p 80:80"'
  -s                Simulate (dry run), only echo to stdout

args:
  IMAGE             Image or URL, e.g., docker://nginx:alpine
  CMD               Optional command/daemon to run
  ARG               Optional arguments to command, e.g., --foreground

EOF
}

service_generate()
{
    image=$1
    cmd=$2
    arg=$3
    svc="pod-$name"
    gen="initctl -fb create $svc"

    if [ -z "$description" ]; then
	description="$name container"
    fi
    # shellcheck disable=SC2209
    if [ -n "$dryrun" ]; then
	gen=cat
	enable=
    fi

    cat <<EOF | $gen
service name:pod :$name podman run --name $name --rm $pmargs $image $cmd $arg -- $description
EOF
    if [ -n "$enable" ]; then
	initctl -fb enable "pod-$name"
    fi
}

while [ "$1" != "" ]; do
    case $1 in
	-d)
	    shift
	    description="$1"
	    ;;
	-e)
	    enable=true
	    ;;
	-h|--help|help)
	    usage
	    exit 0
	    ;;
	-n)
	    shift
	    name="$1"
	    ;;
	-p)
	    shift
	    pmargs="$pmargs $1"
	    ;;
	-s)
	    dryrun=true
	    ;;
	*)
	    break
    esac
    shift
done

image=$1
if [ -z "$image" ]; then
    usage
    exit 1
fi
shift

if [ -z "$name" ]; then
    name=$(echo "$image" | sed 's/\(.*\):.*/\1/g')
fi

# shellcheck disable=SC2068
service_generate "$image" $@
