#!/bin/sh -e

# checking hockeypuck account

uid=`getent passwd hockeypuck | cut -d ":" -f 3`
home=`getent passwd hockeypuck | cut -d ":" -f 6`

# if there is the uid the account is there and we can do
# the sanit(ar)y checks otherwise we can safely create it.

if [ "$uid" ]; then
    # guess??? the checks!!!
    if [ $uid -ge 100 ] && [ $uid -le 999 ]; then
    	echo "hockeypuck uid check: ok"
    else
    	echo "ERROR: hockeypuck account has a non-system uid!"
		exit 1
    fi
    if [ "$home" = "/var/lib/hockeypuck" ]; then
        echo "hockeypuck homedir check: ok"
    else
		echo "ERROR: hockeypuck account has an invalid home directory!"
	exit 1
    fi
else
    # what this might mean?? oh creating a system l^Huser!
    adduser --quiet \
            --system \
            --disabled-password \
            --home /var/lib/hockeypuck \
	    --no-create-home \
	    --shell /bin/bash \
	    --group \
    hockeypuck
fi

if [ "$2" = "" ]; then
    # ch{owning,moding} things around
	mkdir -p /var/log/hockeypuck
	chown -R hockeypuck:hockeypuck /var/log/hockeypuck
	chmod -R 755 /var/log/hockeypuck
	find /var/log/hockeypuck -type f -exec chmod 644 '{}' ';'

    chgrp -R adm /var/log/hockeypuck
    chmod    g+s  /var/log/hockeypuck
fi

# Create conflux prefix tree dir, set permissions
PTREE_DIR=/var/lib/hockeypuck/recon-ptree
if [ ! -d "$PTREE_DIR" ]; then
	mkdir -p $PTREE_DIR
fi
chown -R hockeypuck:hockeypuck /var/lib/hockeypuck

# Create hockeypuck postgres user & database if PostgreSQL is installed
uid=`getent passwd postgres | cut -d ":" -f 3`
if test "$uid" && test -x "/usr/bin/createdb" && test -x "/usr/bin/createuser"; then
	invoke-rc.d postgresql start || true

	echo "Waiting for PostgreSQL to start..."
	for i in {1..10}; do
		sleep 1
		pgpid=$(cat /var/run/postgresql/*.pid)
		[ -e "/proc/$pgpid/net/unix" ] && break
	done
	if [ -e "/proc/$pgpid/net/unix" ]; then
		echo "PostgreSQL started. Setting up Hockeypuck DB..."

		# Create role and database
		su - postgres -c "createuser --no-superuser --no-createrole -d hockeypuck" || true
		su - hockeypuck -c "createdb hkp" || true

		# Create Hockeypuck database & constraints
		su - hockeypuck -c "hockeypuck db --create-tables --create-constraints"

		# Start Hockeypuck
		invoke-rc.d hockeypuck restart
	else
		echo "PostgreSQL did not start. Run 'dpkg-reconfigure hockeypuck' after it is running."
	fi
fi

#DEBHELPER#

exit 0
