#!/bin/bash

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


LOGROOT=/chroot/proxyd/var/log

NLOGROOT=${LOGROOT}/nginx

if [ -d ${NLOGROOT} ]; then
	mkdir -p ${NLOGROOT}/main

	mkdir -p ${NLOGROOT}/daily
	mkdir -p ${NLOGROOT}/daily/main
fi


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 nginx-chroot.service; then
		deb-systemd-helper enable nginx-chroot.service >/dev/null || true
	else
		deb-systemd-helper update-state nginx-chroot.service >/dev/null || true
	fi

	systemctl restart rsyslog
	systemctl daemon-reload

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

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

	### sysvinit

	if [ -x "/etc/init.d/nginx-chroot" ]; then
		update-rc.d nginx-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/proxyd/run /systemd/notify file
/usr/lib/3gsystools/chr_placeholder_check /chroot/proxyd/run /systemd/journal/dev-log file

echo "Checking SSL cert placeholder dirs"
/usr/lib/3gsystools/chr_placeholder_check /chroot/proxyd/etc/ssl /sys dir

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

exit 0
