#!/bin/bash
set -x
export DOCKER_HOST=""
ARGS="$@"

# Extract the network namespace UUID from the command line args provided by
# neutron. Typically of the form (with dnsmasq as an example):
#
# dnsmasq --no-hosts --no-resolv --except-interface=lo \
#   --pid-file=/var/lib/neutron/dhcp/317716b8-919a-4a6f-8db1-78128ec3b100/pid  \
#   --dhcp-hostsfile=/var/lib/neutron/dhcp/317716b8-919a-4a6f-8db1-78128ec3b100/host ...
NETNS=$(ip netns identify)
NAME=neutron-dnsmasq-${NETNS}
CLI="nsenter --net=/run/netns/${NETNS} --preserve-credentials -m -t 1 podman"
LOGGING="--log-driver k8s-file --log-opt path=/var/log/containers/stdouts/${NAME}.log"
CMD='/usr/sbin/dnsmasq -k'
LIST=$($CLI ps -a --filter name=neutron-dnsmasq- --format '{{.ID}}:{{.Names}}:{{.Status}}' | awk '{print $1}')

# Find orphaned containers left for dead after its main process terminated by neutron parent process
# FIXME(cjeanner): https://github.com/containers/libpod/issues/1703
ORPHANTS=$(printf "%s\n" "${LIST}" | grep -E ":(Exited|Created)")
if [ -n "${ORPHANTS}" ]; then
    for orphant in $(printf "%s\n" "${ORPHANTS}" | awk -F':' '{print $1}'); do
        echo "Removing orphaned container ${orphant}"
        $CLI stop ${orphant} || true
        $CLI rm -f ${orphant} || true
    done
fi

# If the NAME is already taken by a container, give it an unique name
printf "%s\n" "${LIST}" | grep -q "${NAME}$" && NAME="${NAME}-$(date +%Y-%m-%d-%H%M%S-%N)"
echo "Starting a new child container ${NAME}"
$CLI run --detach ${LOGGING} \
     -v /var/lib/config-data/puppet-generated/neutron/etc/neutron:/etc/neutron:ro \
     -v /run/netns:/run/netns:shared \
     -v /var/lib/neutron:/var/lib/neutron:shared \
     -v /dev/log:/dev/log \
     --net host \
     --pid host \
     --cgroupns host \
     --privileged \
     -u root \
     --name $NAME \
    registry.redhat.io/rhosp-rhel9/openstack-neutron-dhcp-agent:17.1 \
    $CMD $ARGS
