#!/bin/bash

[[ -n "$DEBUG" ]] && set -x

ACTION="$1"

set -euo pipefail

if [[ -z "$ACTION" ]]
then
    echo "Usage: $0 start|stop"
    exit 1
fi

PUID="$(id -u "${user}")"
PGID="$(id -g "${user}")"

if [ "$ACTION" == "start" ]
then
   docker rm "${name}" || true

    docker run -d \
        --name "${name}" \
        --env "PUID=$PUID" \
        --env "PGID=$PGID" \
        --env "TZ=${timezone}" \
% for k, v in sorted(environment.items()):
        --env "${k}=${v}" \
% endfor
        --network aaarghhh \
% for host_port, container_port in sorted(ports.items()):
        --publish "127.0.0.1:${host_port}:${container_port}" \
% endfor
% for host_path, container_path in sorted(volumes.items()):
%  if host_path.startswith('/'):
        --volume "${host_path}:${container_path}" \
%  else:
        --volume "/var/opt/docker-engine/${name}/${host_path}:${container_path}" \
%  endif
% endfor
        --restart unless-stopped \
% if command:
        "${image}" \
        "${command}"
% else:
        "${image}"
% endif

elif [ "$ACTION" == "stop" ]
then
    docker stop "${name}"

else
    echo "Unknown action $ACTION"
    exit 1
fi

% if node.has_bundle('nftables'):
systemctl reload nftables
% endif