#!/bin/sh

POLIPOUSER=polipo
POLIPOGROUP=polipo
UID=173
GID=${UID}

POLIPOCACHE=/var/cache/polipo
POLIPOLOG=/var/log/polipo
PPIDDIR=/var/run/polipo/
POLIPOPID=/var/run/polipo/polipo.pid

if [ "$2" = "PRE-INSTALL" ]; then

	if [ "/etc/rc.subr" = "" ]; then
		echo "=> Port requires /etc/rc.subr (native or port/sysutils/rc_subr)!"
		echo "=> If you want to install without you should modify startup script and pkg-install."
		exit 1
	fi

	if fgrep "polipo" "/etc/newsyslog.conf" 2>/dev/null 1>&2; then
		if ! fgrep "polipo.pid" "/etc/newsyslog.conf" 2>/dev/null 1>&2; then
			echo "==> ERROR: Previous installation left an invalid entry in /etc/newsyslog.conf."
			echo "==> Please remove the polipo line from this file and try again."
			exit 1
		fi
	fi

	if ! pw groupshow "$POLIPOGROUP" 2>/dev/null 1>&2; then
		if pw groupadd $POLIPOGROUP -g ${GID} ; then
			echo "=> Added group \"$POLIPOGROUP\"."
		else
			echo "=> Adding group \"$POLIPOGROUP\" failed..."
			exit 1
		fi
	fi

	if ! pw usershow "$POLIPOUSER" 2>/dev/null 1>&2; then
		if pw useradd $POLIPOUSER -u ${UID} -g $POLIPOGROUP -h - \
			-s "/sbin/nologin" -d "/nonexistent" \
			-c "polipo web cache"; \
		then
			echo "=> Added user \"$POLIPOUSER\"."
		else
			echo "=> Adding user \"$POLIPOUSER\" failed..."
			exit 1
		fi
	fi

elif [ "$2" = "POST-INSTALL" ]; then

	if [ ! -d "$POLIPOCACHE" ]; then
		mkdir -p "$POLIPOCACHE" || exit 1
		chown "$POLIPOUSER:$POLIPOGROUP" "$POLIPOCACHE" || exit 1
		chmod 0770 "$POLIPOCACHE" || exit 1
	fi

	if [ ! -d "$PPIDDIR" ]; then
		mkdir -p "$PPIDDIR" || exit 1
		chgrp "$POLIPOGROUP" "$PPIDDIR" || exit 1
		chmod g+w "$PPIDDIR" || exit 1
	fi

	if [ ! -f "$POLIPOLOG" ]; then
		touch "$POLIPOLOG" || exit 1
		chown "$POLIPOUSER" "$POLIPOLOG" || exit 1
		chmod 0640 "$POLIPOLOG" || exit 1
	fi


	if ! fgrep "${POLIPOLOG}" "/etc/newsyslog.conf" 2>/dev/null 1>&2; then
	echo "${POLIPOLOG}		${POLIPOUSER}:		640  3     100	*     J     $POLIPOPID 30" >> "/etc/newsyslog.conf" || exit 1
	fi

fi

exit 0
