#!/bin/sh -e
#DEBHELPER#

# set up pcpqa user
#
if which systemd-sysusers >/dev/null 2>&1
then
    # use user pcpqa controls installed in /usr/lib/sysusers.d to
    # create user and group
    if ! systemd-sysusers
    then
	echo >&2 "pcp-testsuite.postinstall: Error: systemd-sysusers failed to create pcpqa user"
	exit 1
    fi
    # older versions of systemd-sysusers don't set the login shell to
    # anything useful
    #
    if getent passwd pcpqa | grep  -q '/nologin'
    then
	for shell in bash sh
	do
	    exec=`which $shell 2>/dev/null`
	    if [ -n "$exec" ]
	    then
		if chsh -s "$exec" pcpqa
		then
		    break
		else
		    echo >&2 "pcp-testsuite.postinstall: Warning: failed to change shell to $exec for pcpqa user"
		fi
	    fi
	done
    fi
elif which useradd >/dev/null 2>&1
then
    # old-style
    #
    if ! getent group pcpqa >/dev/null
    then
	if ! groupadd -r pcpqa
	then
	    echo >&2 "pcp-testsuite.postinstall: Error: groupadd failed to create pcpqa group"
	    exit 1
	fi
    fi
    if ! getent passwd pcpqa >/dev/null
    then
	if ! useradd -c "PCP Quality Assurance" -g pcpqa -d /var/lib/pcp/testsuite -m -r -s /bin/bash pcpqa
	then
	    echo >&2 "pcp-testsuite.postinstall: Error: useradd failed to create pcpqa user"
	    exit 1
	fi
    fi
else
    echo >&2 "pcp-testsuite.postinstall: Error: no systemd-sysusers or useradd: cannot create pcpqa user"
    exit 1
fi

chown -RH pcpqa:pcpqa /var/lib/pcp/testsuite 2>/dev/null || true
