#!/bin/bash

# create elasticsearch user
getent group elasticsearch >/dev/null 2>&1 ||
	addgroup --system elasticsearch
getent passwd elasticsearch >/dev/null 2>&1 ||
	adduser --system --home /nonexistent --no-create-home --disabled-password --shell /bin/false --ingroup elasticsearch elasticsearch
#getent passwd elasticsearch |grep "elasticsearch user" >/dev/null 2>&1 ||
#	chfn -f "elasticsearch user" elasticsearch


#LOGROOT=/chroot/elasticd/var/log
#NLOGROOT=${LOGROOT}/elasticsearch

if ! [ -d /chroot/elasticd/run/systemd ]; then
	mkdir /chroot/elasticd/run/systemd
fi

if ! [ -f /chroot/elasticd/run/systemd/notify ]; then
	touch /chroot/elasticd/run/systemd/notify
fi

sysctl -p /etc/sysctl.d/elasticsearch-chroot.conf


INITSYS=`readlink -f /proc/1/exe`
if [ "$INITSYS" == "/lib/systemd/systemd" -o "$INITSYS" == "/usr/lib/systemd/systemd" ]; then

	# systemd
	if deb-systemd-helper --quiet was-enabled elasticsearch-chroot.service; then
		deb-systemd-helper enable elasticsearch-chroot.service >/dev/null || true
	else
		deb-systemd-helper update-state elasticsearch-chroot.service >/dev/null || true
	fi

	systemctl restart rsyslog
	systemctl daemon-reload

	if ! [ -e /chroot/elasticd/dev/log ]; then
		ln -s ../run/systemd/journal/dev-log /chroot/elasticd/dev/log
	fi

elif [ "$INITSYS" == "/sbin/init" ]; then

	### sysvinit

	if [ -x "/etc/init.d/elasticsearch-chroot" ]; then
		update-rc.d elasticsearch-chroot defaults >/dev/null
	fi

	if [ -x "/etc/init.d/rsyslog" ]; then
		/etc/init.d/rsyslog restart
	fi

else
	echo "No init system found, check manually"
fi

echo "Checking systemd socket placeholders"
/usr/lib/3gsystools/chr_placeholder_check /chroot/elasticd/run /systemd/notify file
/usr/lib/3gsystools/chr_placeholder_check /chroot/elasticd/run /systemd/journal/dev-log file

echo "Checking fstab"
/usr/local/sbin/fstab-chr

exit 0
