#!/bin/sh
set -eu

if [ -f /etc/bird/envvars ]; then
  # shellcheck disable=SC1091
  . /etc/bird/envvars
fi

BIRD_RUN_USER="${BIRD_RUN_USER:-bird}"
BIRD_RUN_GROUP="${BIRD_RUN_GROUP:-bird}"
if [ -z "${BIRD_ARGS:-}" ]; then
  BIRD_ARGS="-c /etc/bird/bird-init.conf"
fi

if [ -x /usr/lib/bird/prepare-environment ]; then
  /usr/lib/bird/prepare-environment
fi

/usr/sbin/bird -p $BIRD_ARGS

if [ -d /bgp/bgpdata ]; then
  find /bgp/bgpdata -maxdepth 1 -type f -name '*.lock' -exec rm -f {} \;
fi

if [ -f /bgp/bird.conf ]; then
  sed -i 's/^mrtdump/#mrtdump/' /bgp/bird.conf
  sed -i '/^protocol mrt {/,/^}$/ s/^/#/' /bgp/bird.conf
fi

exec 2>&1
exec /usr/sbin/bird -f -u "$BIRD_RUN_USER" -g "$BIRD_RUN_GROUP" $BIRD_ARGS
