#!/bin/sh
# ugly hack b/c otrs.Daemon.pl can't be run in the foreground

if [ -f ./data/default.env ]; then
  . ./data/default.env
fi
if [ -f /etc/default/otrs ]; then
  . /etc/default/otrs
fi
if [ -f ./data/override.env ]; then
  . ./data/override.env
fi

DAEMON_USER="${DAEMON_USER:-otrs}"
DAEMON_GROUP='www-data'
RUN_DIR='/run/otrs'

mkdir -p "$RUN_DIR"
chown "${DAEMON_USER}:${DAEMON_GROUP}" "$RUN_DIR"
chmod 0770 "$RUN_DIR"

trap '/usr/share/otrs/bin/otrs.Daemon.pl stop' EXIT
/usr/share/otrs/bin/otrs.Daemon.pl start

sleep 2

while true; do
  if ! /usr/share/otrs/bin/otrs.Daemon.pl status | grep -Fiq 'daemon running'; then
    exit 1
  fi
  sleep 1
done
