#!/bin/bash

# load system wide environment defaults
if [ -f /etc/s6-run-script-default.env ]; then
  . /etc/s6-run-script-default.env
fi
# load maintainer defaults which are provided in the service definition
if [ -f ./data/default.env ]; then
  . ./data/default.env
fi
# load universal default for this service, the sysadmin is allowed to change them
if [ -f "/etc/default/$1" ]; then
  . "/etc/default/$1"
fi
# load maintainer overrides which force specific fields to not be overridden
if [ -f ./data/override.env ]; then
  . ./data/override.env
fi

# set environment variables to reasonable values if not provided
LOGGER_OPTIONS="${LOGGER_OPTIONS:-T s100000000 n10}"
# by default the log subdirectory equals the provided argument
LOGGER_DIRECTORY="${LOGGER_DIRECTORY:-/var/log/$1}"
# the default user of the process is root if not configured by the environment
LOGGER_USER="${LOGGER_USER:-root}"
LOGGER_GROUP="${LOGGER_GROUP:-syslog}"
NOTIFICATION_FD="$(cat ./notification-fd)"

# try to change ownership of an existing log directory
mkdir -p "$LOGGER_DIRECTORY"
chown "${LOGGER_USER}:${LOGGER_GROUP}" "$LOGGER_DIRECTORY" || true
# make log directory world-executable so that the daemon user can access
# subdirectories (namely the "extra" directory intended for application logs)
chmod o+x "$LOGGER_DIRECTORY" || true

# start the logger
exec -c s6-setuidgid ${LOGGER_USER} s6-log -d"$NOTIFICATION_FD" -- ${LOGGER_OPTIONS} ${LOGGER_DIRECTORY}
