#!/bin/bash
set -e
cfg='/etc/mediatomb.conf'
for i in MT_USER MT_GROUP MT_LOGFILE MT_HOME MT_CFGDIR MT_PORT
do
	if test -z "${!i}"
	then
		echo "${i}= must be set, either in ${cfg} or /etc/systemd/system/mediatomb.service.d/tune.conf"
		exit 1
	fi
done
if test "${MT_INTERFACE}" = "NOT_SET" || test "${MT_INTERFACE}" = ""
then
	echo "Please edit ${cfg} and change the MT_INTERFACE variable to your network device (eth0, eth1, etc.)"
	exit 1
fi
IFACE_IP="`ip -oneline -family inet addr show dev ${MT_INTERFACE} | sed -n 's@\(^[0-9]\+:[[:blank:]]\+[^[:blank:]]\+[[:blank:]]\+inet[[:blank:]]\+\)\([^/]\+\)\(.*\)@\2@p'`"
if test -z "${IFACE_IP}"
then
	echo "No IPv4 found on MT_INTERFACE ${MT_INTERFACE}"
	exit 1
fi
###############################
# make sure to run it as $MT_USER
MEDIATOMB="-u ${MT_USER} -g ${MT_GROUP} -l ${MT_LOGFILE} -m ${MT_HOME} -f ${MT_CFGDIR} -p ${MT_PORT}"

# Start daemon.
echo "Applying multicast settings to ${MT_INTERFACE}"
# those settings are necessary for us to react to M-SEARCH requests
ip route add 239.0.0.0/8 dev ${MT_INTERFACE}
ip link set dev ${MT_INTERFACE} allmulticast on

mkdir -vp "${MT_HOME}/${MT_CFGDIR}"
chown -v "${MT_USER}:${MT_GROUP}" "${MT_HOME}/${MT_CFGDIR}"

echo "Starting mediatomb"
exec mediatomb ${MEDIATOMB} -i ${IFACE_IP} ${MT_OPTIONS}
