#!/bin/bash

dir='/nquakesv'

remote_ip=$(curl http://myip.dnsomatic.com)
[ -n "$hostdns" ] || hostdns=$remote_ip

echo "===== nQuakeSV Configuration ====="

echo "Setting server name: ${HOSTNAME}"
echo $hostname > ~/.nquakesv/hostname
/bin/sed -i "s/hostname .*/hostname ${HOSTNAME}/" ktx/port1.cfg
/bin/sed -i "s/.*k_motd1 .*/set k_motd1 \"${HOSTNAME}\"/" ktx/port1.cfg
/bin/sed -i "s/hostname .*/hostname ${HOSTNAME}/" qtv/qtv.cfg
/bin/sed -i "s/set hostname .*/set hostname \"${HOSTNAME}\"/" qwfwd/qwfwd.cfg

echo "Setting server hostname: ${HOSTDNS}"
echo $hostdns > ~/.nquakesv/hostdns
echo $remote_ip > ~/.nquakesv/ip
#/bin/sed -i "s/qtv .*/qtv ${HOSTDNS}:28501/" qtv/qtv.cfg
/bin/sed -i "s/qtv .*/qtv 127.0.0.1:28501/" qtv/qtv.cfg
/bin/sed -i "s/sv_serverip .*/sv_serverip \"${remote_ip}:28501\"/" ktx/port1.cfg

echo "Setting server admin: ${ADMINNAME} <${ADMINEMAIL}>"
echo "${ADMINNAME} <${ADMINEMAIL}>" > ~/.nquakesv/admin
/bin/sed -i "s/sv_admininfo .*/sv_admininfo \"${ADMINNAME} <${ADMINEMAIL}>\"/" ktx/port1.cfg

echo "Setting rcon password: ${RCON}"
/bin/sed -i "s/rcon_password \".*\".*/rcon_password \"${RCON}\"/" ${dir}/ktx/pwd.cfg

echo "Setting Qtv password: ${QTVPW}"
/bin/sed -i "s/admin_password .*/admin_password ${QTVPW}/" qtv/qtv.cfg

echo "Enabled FFA: ${FFA}"
/bin/sed -i "s/set k_matchless .*/set k_matchless ${FFA}/" ktx/port1.cfg
if [ ${FFA} == 1 ]; then
/bin/sed -i "s/set k_use_matchless_dir .*/set k_use_matchless_dir 1/" ktx/port1.cfg
/bin/sed -i "s/set k_ml_.*//" ktx/configs/usermodes/matchless/default.cfg
echo 'set k_ml_0 "dm1"' >> ktx/configs/usermodes/matchless/default.cfg
#echo 'set k_ml_0 "dm2"' >> ktx/configs/usermodes/matchless/default.cfg
echo 'set k_ml_0 "dm3"' >> ktx/configs/usermodes/matchless/default.cfg
echo 'set k_ml_0 "dm4"' >> ktx/configs/usermodes/matchless/default.cfg
echo 'set k_ml_0 "dm5"' >> ktx/configs/usermodes/matchless/default.cfg
echo 'set k_ml_0 "dm6"' >> ktx/configs/usermodes/matchless/default.cfg
fi

echo "=================================="

/usr/bin/supervisorctl start nquakesv:*

exit 0
