#!/bin/sh

set -e

USER="stunnel4"
CHOWN="/bin/chown"
#USERDEL="/usr/sbin/userdel"
ADDUSER="/usr/sbin/adduser"
ID="/usr/bin/id"
GROUPMOD="/usr/sbin/groupmod"
#GROUPDEL="/usr/sbin/groupdel"

###
# 1. get current stunnel uid and gid if user exists.
set -e
if $ID $USER > /dev/null 2>&1; then
   IUID=`$ID --user $USER`
   IGID=`$ID --group $USER`
else
   IUID="NONE"
   IGID="NONE"
fi

###
# 2. Ensure that no standard account or group will remain before adding the
#    new user
#if [ "$IUID" != "NONE" ]; then # remove existing user
#  $USERDEL $USER
#fi

#if $GROUPMOD $USER > /dev/null 2>&1; then 
#  $GROUPDEL $USER;
#fi

if [ "$IUID" = "NONE" ]; then
  $ADDUSER --system --disabled-password --disabled-login	\
           --home /var/run/stunnel4			\
	   --no-create-home --group $USER
fi

# /var/run/stunnel4 is not a directory, create it...
if ! test -d /var/run/stunnel4; then
  rm -rf /var/run/stunnel4;
  mkdir /var/run/stunnel4
fi
$CHOWN $USER:$USER /var/run/stunnel4 || true

# /var/log/stunnel4 is not a directory, create it...
if ! test -d /var/log/stunnel4; then
  rm -rf /var/log/stunnel4;
  mkdir /var/log/stunnel4
fi
$CHOWN -R $USER:$USER /var/log/stunnel4

# /var/lib/stunnel4 is not a directory, create it...
if ! test -d /var/lib/stunnel4; then
  rm -rf /var/lib/stunnel4;
  mkdir /var/lib/stunnel4
fi
$CHOWN -R $USER:$USER /var/lib/stunnel4

if ! test -f /var/log/stunnel4/stunnel.log; then
  touch /var/log/stunnel4/stunnel.log
  $CHOWN -R $USER:$USER /var/log/stunnel4/stunnel.log
fi

#DEBHELPER#
