#!/bin/sh

set -e

USERGROUP="odchub"
OPENDC_TEMP="tmp"

LOGFILE="/var/log/opendchub"
HOMEDIR="/var/lib/opendchub/homedir"
RUNDIR="/var/lib/opendchub/rundir"

User () {
	# Create opendchub user and group
	if ! getent passwd ${USERGROUP} >/dev/null; then
		adduser --quiet --system --group --no-create-home \
		    --home ${HOMEDIR} ${USERGROUP}
	fi
}

Config() {
	# Configure permissions on conffiles - the opendchub daemon needs to
	# write back to the file and they contain passwords.
	for FILE in config motd
	do
		if ! dpkg-statoverride --list --quiet /etc/opendchub/${FILE} >/dev/null
		then
			dpkg-statoverride --force --quiet --update \
			    --add root ${USERGROUP} 0660 /etc/opendchub/${FILE}
		fi
	done
}

Logfile () {
	if [ ! -e ${LOGFILE} ]
	then
		touch ${LOGFILE}
	fi

	chown ${USERGROUP}:${USERGROUP} ${LOGFILE}
}

Rundir () {
	mkdir -p ${RUNDIR}
	chown ${USERGROUP}:${USERGROUP} ${RUNDIR}
}

Homedir () {
	# Create and populate the false home directory. We do this because the
	# opendchub daemon insists on reading from ~/.opendchub/foo and the
	# "working directory" switch is broken.

	rm -rf ${HOMEDIR}
	mkdir -p ${HOMEDIR}

	# Ensure config files are not hidden behind a dotfile
	ln -s ${HOMEDIR} "${HOMEDIR}/.opendchub"

	ln -s ${LOGFILE} "${HOMEDIR}/log"
	ln -s ${RUNDIR} "${HOMEDIR}/${OPENDC_TEMP}"

	# Configure configuration files
	for FILE in config motd
	do
		ln -s /etc/opendchub/${FILE} ${HOMEDIR}/${FILE}
	done

	# Configure run-time files. The "1" variants are used by the daemon as
	# temporary files.
	for FILE in allowlist banlist linklist nickbanlist odchlist op_permlist reglist
	do
		ln -s ${RUNDIR}/${FILE} ${HOMEDIR}/${FILE}
		ln -s ${RUNDIR}/${FILE}1 ${HOMEDIR}/${FILE}1
	done

        # Configure scripts directory
        ln -s /etc/opendchub/scripts ${HOMEDIR}/scripts
}

User
Config
Logfile
Rundir
Homedir

#DEBHELPER#
