#!/bin/sh
set -e
set -u

# eturnal STUN/TURN server.
#
# Copyright (c) 2020-2022 Holger Weiss <holger@zedat.fu-berlin.de>.
# Copyright (c) 2020-2022 ProcessOne, SARL.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# CONFIGURATION SECTION:

user="${ETURNAL_USER:-_eturnal}"
bin_prefix="${ETURNAL_BIN_PREFIX:-/usr/lib/eturnal}"
etc_prefix="${ETURNAL_ETC_PREFIX:-}"
epmd_address="${ERL_EPMD_ADDRESS:-}"
dist_port="${ERL_DIST_PORT:-}"
config_file="$etc_prefix/etc/eturnalctl.cfg"

# END OF CONFIGURATION SECTION.

if [ -e "$config_file" ]
then
    . "$config_file"
fi
if [ -z "${ERL_EPMD_ADDRESS:-}" ] && [ -n "$epmd_address" ]
then
    ERL_EPMD_ADDRESS="$epmd_address"
    export ERL_EPMD_ADDRESS
fi
if [ -z "${ERL_DIST_PORT:-}" ] && [ -n "$dist_port" ]
then
    ERL_DIST_PORT="$dist_port"
    export ERL_DIST_PORT
fi
if [ -z "${ETURNAL_ETC_PREFIX:-}" ] && [ -n "$etc_prefix" ]
then
    ETURNAL_ETC_PREFIX="$etc_prefix"
    export ETURNAL_ETC_PREFIX
fi
if [ -x "$bin_prefix/bin/eturnal" ]
then
    cmd="$bin_prefix/bin/eturnal"
else
    myself="$(readlink "$0" || :)" # Not all readlink(1)s support "-f".
    if [ -z "$myself" ]
    then
        myself="$0"
    fi
    bin_prefix="$(cd "$(dirname "$myself")/.." && pwd -P)"
    if [ -x "$bin_prefix/bin/eturnal" ]
    then
        cmd="$bin_prefix/bin/eturnal"
    else
        cmd='eturnal' # Rely on $PATH.
    fi
fi
if [ "$(id -u)" = '0' ]
then
    arg="$(printf '%s' "$*" | sed 's/[^[:alnum:][:space:]]/\\&/g')"
    exec su "$user" -c "$cmd $arg"
else
    exec "$cmd" "$@"
fi
