#!/bin/bash

 case "$1" in
   install|upgrade)
 
   # If the package has default file it could be sourced, so that
   # the local admin can overwrite the defaults
 
   [ -f "/etc/default/jetty9" ] && . /etc/default/jetty9
 
   # Sane defaults:
 
   [ -z "$SERVER_HOME" ] && SERVER_HOME=/usr/share/jetty9
   [ -z "$SERVER_USER" ] && SERVER_USER=jetty
   [ -z "$SERVER_NAME" ] && SERVER_NAME="Jetty-9 Http and Servlet Engine"
   [ -z "$SERVER_GROUP" ] && SERVER_GROUP=jetty
 
   # Groups that the user will be added to, if undefined, then none.
   ADDGROUP=""
 
   # create user to avoid running server as root
   # 1. create group if not existing
   if ! getent group | grep -q "^$SERVER_GROUP:" ; then
      echo -n "Adding group $SERVER_GROUP.."
      addgroup --quiet --system $SERVER_GROUP 2>/dev/null ||true
      echo "..done"
   fi
   # 2. create homedir if not existing
   test -d $SERVER_HOME || mkdir $SERVER_HOME
   # 3. create user if not existing
   if ! getent passwd | grep -q "^$SERVER_USER:"; then
     echo -n "Adding system user $SERVER_USER.."
     adduser --quiet \
             --system \
             --ingroup $SERVER_GROUP \
             --no-create-home \
             --disabled-password \
             $SERVER_USER 2>/dev/null || true
     echo "..done"
   fi
   # 4. adjust passwd entry
   usermod -c "$SERVER_NAME" \
           -d $SERVER_HOME   \
           -g $SERVER_GROUP  \
              $SERVER_USER
   # 5. adjust file and directory permissions
   if ! dpkg-statoverride --list $SERVER_HOME >/dev/null
   then
       chown -R $SERVER_USER:$SERVER_GROUP $SERVER_HOME
       chmod u=rwx,g=rxs,o= $SERVER_HOME
   fi
   # 6. Add the user to the ADDGROUP group
   if test -n $ADDGROUP
   then
       if ! groups $SERVER_USER | cut -d: -f2 | \
          grep -qw $ADDGROUP; then
            adduser $SERVER_USER $ADDGROUP
       fi
   fi
   ;;
   configure)