#!/bin/sh

#set -vx

PKG_BATCH=${BATCH:=NO}
PKG_PREFIX=${PKG_PREFIX:=/usr/local}

SERVERVARDIR=/var/spool/afbackup

#
# create 'afbackup' user before installing
#

dlg() {
	if [ X"${NONINTERACTIVE}" != "XYES" ]; then
		dialog "$@"
		return $?
	else
		i=1
		while [ $i -lt $# ]; do
			eval 'arg="$'$i'"'
			if [ $arg = '--msgbox' ]; then
				eval 'echo "$'$(($i+1))'"'
				return 0
			fi
			i=$(($i+1))
		done
	fi
	return 0;
}

create() {
	if [ ! -x /usr/sbin/pw ]; then
		dlg --msgbox "Please add a user named \`afbackup' before installing this package." 6 60
		exit 69
	fi

	if [ -x /sbin/nologin ]; then
		shell=/sbin/nologin
	else
		shell=/nonexistent
	fi
	if ! pw show user afbackup -q >/dev/null; then
		if ! dlg --clear --yesno "There is no user afbackup on your system.\n\nDo you want it to be created?" 7 60; then
			dlg --msgbox "Please add a user named \`afbackup' before installing this package." 6 60
			exit 69
		fi
		uid=100
		while pw show user -u ${uid} -q >/dev/null; do
			uid=`expr ${uid} + 1`
		done
		if ! pw add user afbackup -u ${uid} -g operator -d "/nonexistent" \
				-c "AFBackup System Owner" -s "${shell}" \
				; then
			e=$?
			dlg --msgbox "Failed to add an account for \`afbackup' user. Please add it manually." 6 60
			exit ${e}
		fi
		echo "==>  Added user \`afbackup' (id ${uid})"
	else
		if ! pw mod user afbackup -g operator -d "/nonexistent" \
				-c "AFBackup System Owner" -s "${shell}" \
				; then
			e=$?
			dlg --msgbox "Failed to update user \`afbackup'." 6 60
			exit ${e}
		fi
		echo "==>  Updated user \`afbackup'."
	fi
}

case $2 in
	PRE-INSTALL)
		create
		;;
	POST-INSTALL)
                case $1 in
                        *-client*)
                        ;;
                        *)
                        if [ ! -d ${SERVERVARDIR} ]; then
				install -d -o afbackup -g operator ${SERVERVARDIR}
				touch ${SERVERVARDIR}/readonly_tapes
			fi
                        ;;
                esac

		;;
esac
