#!/bin/bash

# redirect stderr to stdout
exec 2>&1

# 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
# by default DAEMON_DEFAULT equals the provided argument
DAEMON_DEFAULT="${DAEMON_DEFAULT:-$1}"
# load universal default for this service, the sysadmin is allowed to change them
if [ -f "/etc/default/$DAEMON_DEFAULT" ]; then
  . "/etc/default/$DAEMON_DEFAULT"
fi
# load maintainer overrides which force specific fields to not be overridden
if [ -f ./data/override.env ]; then
  . ./data/override.env
fi

DAEMON_LOG_DIRECTORY="${DAEMON_LOG_DIRECTORY:-/var/log/$1/extra}"

# by default DAEMON equals the provided argument
DAEMON="${DAEMON:-$1}"
shift
DAEMON_FIXED_OPTIONS="${DAEMON_FIXED_OPTIONS:-}"
DAEMON_OPTIONS="${DAEMON_OPTIONS:-}"
DAEMON_ARGS="${DAEMON_ARGS:-}"
DAEMON_DIRECTORY="${DAEMON_DIRECTORY:-.}"
# the default user of the process is root if not configured by the environment
DAEMON_USER="${DAEMON_USER:-root}"
DAEMON_RUN_USER="${DAEMON_RUN_USER:-}"
DAEMON_LOG_USER="${DAEMON_LOG_USER:-$DAEMON_USER}"

# create process run directory
DAEMON_RUN_DIRECTORY="/run/$(basename "$DAEMON")"
mkdir -p "$DAEMON_RUN_DIRECTORY"
if [ -n "$DAEMON_RUN_USER" ]; then
  chown "$DAEMON_RUN_USER" "$DAEMON_RUN_DIRECTORY"
else
  chown "$DAEMON_USER" "$DAEMON_RUN_DIRECTORY"
fi

# create extra log directory (for logs written by the service itself)
mkdir -p "$DAEMON_LOG_DIRECTORY"
chown "$DAEMON_LOG_USER" "$DAEMON_LOG_DIRECTORY" || true

mkdir -p "$DAEMON_DIRECTORY"
cd "$DAEMON_DIRECTORY" || exit 1

# apply process limits (/!\ DAEMON_LIMITS can hijack control)
exec s6-softlimit ${DAEMON_LIMITS} -- s6-setuidgid ${DAEMON_USER} ${DAEMON} ${DAEMON_OPTIONS} ${DAEMON_FIXED_OPTIONS} ${DAEMON_ARGS} "$@"
