#!/bin/sh -e
# This script creates a minimal configuration which allows to start innd.
# It must be run from the top level directory of the Debian source package.

INN_PKG_ROOT="$(pwd)/debian/inn2"
INN_LD_LIBRARY_PATH="$(pwd)/debian/inn2/usr/lib/news/:$(pwd)/debian/inn2-inews/usr/lib/news/"

mkdir -p /tmp/news/etc/ /tmp/news/spool/ /tmp/news/spool/incoming/ /tmp/news/lib/ /tmp/news/lib/http/ /tmp/news/run/ /tmp/news/lib/log/

export INNCONF=/tmp/news/etc/inn.conf
[ -e $INNCONF ] || \
cat <<END > $INNCONF
mta:				/bin/true
pathhost:			test
patharticles:			/tmp/news/spool/articles
pathbin:			$INN_PKG_ROOT/usr/lib/news/bin
pathdb:				/tmp/news/lib
pathetc:			/tmp/news/etc
pathnews:			/tmp/news/lib
pathrun:			/tmp/news/run
pathspool:			/tmp/news/spool
enableoverview:			false
hismethod:			hisv6
END

[ -e /tmp/news/etc/storage.conf ] || \
cat <<END > /tmp/news/etc/storage.conf
method tradspool {
    newsgroups: *
    class: 0
}
END

[ -e /tmp/news/etc/incoming.conf ] || \
echo 'peer ME { hostname: "127.0.0.1, ::1" }' > /tmp/news/etc/incoming.conf

[ -e /tmp/news/etc/newsfeeds ] || \
echo 'ME:!*::' > /tmp/news/etc/newsfeeds

[ -e /tmp/news/spool/tradspool.map ] || \
: > /tmp/news/spool/tradspool.map

[ -e /tmp/news/lib/active ] || \
cp samples/active.minimal /tmp/news/lib/active

if [ ! -e /tmp/news/lib/history ]; then
  : > /tmp/news/lib/history
  chown news: -R /tmp/news/
  LD_LIBRARY_PATH="$INN_LD_LIBRARY_PATH" \
    $INN_PKG_ROOT/usr/lib/news/bin/makehistory
fi

if [ ! -e /tmp/news/ctlinnd ]; then
  cat <<END > /tmp/news/ctlinnd
#!/bin/sh -e
export LD_LIBRARY_PATH="$INN_LD_LIBRARY_PATH"
export INNCONF=$INNCONF
exec $INN_PKG_ROOT/usr/lib/news/bin/ctlinnd "\$@"
END
  chmod +x /tmp/news/ctlinnd
fi

chown news: -R /tmp/news/

systemctl reset-failed testinn.service 2> /dev/null || true
systemd-run --uid=9 --gid=9 --wait --pty -u testinn \
  systemd-socket-activate -l 1199 \
  -E LD_LIBRARY_PATH="$INN_LD_LIBRARY_PATH" \
  -E INNCONF=$INNCONF \
  $INN_PKG_ROOT/usr/lib/news/bin/innd -f

#  valgrind --log-file=/tmp/news/valgrind.out \

exit

