#!/bin/sh
set -e

: ${TMPDIR:=/tmp}

# What are we doing here?

[ "$1" = abort-upgrade ] && exit 0

#

addpasswd() {
    entry="$1"

    usr=`echo $entry | cut -d: -f1`
    uid=`echo $entry | cut -d: -f3`
    gid=`echo $entry | cut -d: -f4`

    if [ "`grep \"^$usr:\" /etc/passwd`" = "" ]
    then
    	(
	printed=0
	while read line
        do
	    lusr=`echo $line | cut -d: -f1`

	    if [ $printed -eq 0 ]
	    then
		if [ "`echo $line | cut -d: -f1`" = "+" ]
		then
		    echo $entry
		    printed=1
		else
		    luid=`echo $line | cut -d: -f3`
		    if [ $luid -gt $uid ]
		    then
		    	echo $entry
		    	printed=1
		    fi
		fi
	    fi
	    if [ $usr != $lusr ]
	    then
		echo $line
	    fi
    	done
	if [ $printed -eq 0 ]
	then
	    echo $entry
	fi
	) </etc/passwd >${TMPDIR}/.passwd.$$ &&
	    mv ${TMPDIR}/.passwd.$$ /etc/passwd
    fi
}

addgroup() {
    entry="$1"

    grp=`echo $entry | cut -d: -f1`
    gid=`echo $entry | cut -d: -f3`

    if [ "`grep \"^$grp:\" /etc/group`" = "" ]
    then
    	(
	printed=0
	while read line
        do
	    lgrp=`echo $line | cut -d: -f1`

	    if [ $printed -eq 0 ]
	    then
		if [ "`echo $line | cut -d: -f1`" = "+" ]
		then
		    echo $entry
		    printed=1
		else
		    lgid=`echo $line | cut -d: -f3`
		    if [ $lgid -gt $gid ]
		    then
		    	echo $entry
		    	printed=1
		    fi
		fi
	    fi
	    if [ $grp != $lgrp ]
	    then
		echo $line
	    fi
    	done
	if [ $printed -eq 0 ]
	then
	    echo $entry
	fi
	) </etc/group >${TMPDIR}/.group.$$ &&
	    mv ${TMPDIR}/.group.$$ /etc/group
    fi
}

wwwdata="`2>/dev/null grep '^www-data:' /etc/passwd`"
if [ -z "$wwwdata" ]
then
    testuid=33
    testgid=33
else
    testuid=`echo $wwwdata | cut -d: -f3`
    testgid=`echo $wwwdata | cut -d: -f4`
fi

addpasswd 'www-data:*:33:33:www-data:/var/www:/bin/sh'
addgroup 'www-data:*:33:'

# See which version was installed.

if [ "$1" = install -o "$1" = upgrade ] && [ "$2" != "" ]
then
	if [ -f /etc/init.d/apache ]
	then
		initd=apache
	else
		initd=httpd
	fi

	if [ ! -d /etc/apache -a -d /etc/httpd ]
	then
	    echo Copying existing configuration from "\`/etc/httpd'" to "\`/etc/apache'..."
	    mkdir -m 755 /etc/apache &&
		(cd /etc/httpd; tar cf - .) | (cd /etc/apache; tar xpf -)
	fi
else
	initd=apache
fi

exit 0
