#!/bin/bash

TUXUMBACKUPUSER=tuxumbackup
TUXUMBACKUPGROUP=backup
GROUPLIST="disk tape cdrom floppy operator fuse plugdev"

for i in ${GROUPLIST}
do
	EXIST=`cat /etc/group | awk -F ':' '{print $1}' | grep -w $i`
	if [ -n "${EXIST}" ]
	then
		if [ -z "${EXISTINGGROUPS}" ]
		then
			EXISTINGGROUPS=${i}
		else
			EXISTINGGROUPS="${EXISTINGGROUPS},${i}"
		fi
	else
		if [ -z "${NOTEXISTINGGROUPS}" ]
		then
			NOTEXISTINGGROUPS=${i}
		else
			NOTEXISTINGGROUPS="${NOTEXISTINGGROUPS},${i}"
			PLURAL=true
		fi
	fi
done

EXISTUSER=`cat /etc/passwd | awk -F ':' '{print $1}' | grep -w ${TUXUMBACKUPUSER}`
EXISTGROUP=`cat /etc/group | awk -F ':' '{print $1}' | grep -w ${TUXUMBACKUPGROUP}`

if [ -z "${EXISTGROUP}" ]
then
	groupadd ${TUXUMBACKUPGROUP}
fi

if [ -z "${EXISTUSER}" ]
then
	useradd -m -r -s /bin/bash -g ${TUXUMBACKUPGROUP} -G ${EXISTINGGROUPS} ${TUXUMBACKUPUSER}
else
	usermod -m -s /bin/bash -g ${TUXUMBACKUPGROUP} -G ${EXISTINGGROUPS} ${TUXUMBACKUPUSER}
fi

if [ -n "${NOTEXISTINGGROUPS}" ]
then
	if [ "${PLURAL}" == "true" ]
	then
		echo "Warning: cannot add user ${TUXUMBACKUPUSER} to following groups: ${NOTEXISTINGGROUPS}"
	else
		echo "Warning: cannot add user ${TUXUMBACKUPUSER} to the group ${NOTEXISTINGGROUPS}"
	fi
fi

for i in /var/log/tuxum-backup /var/tuxum-backup /etc/tuxum-backup
do
	mkdir -p $i
	chown -R ${TUXUMBACKUPUSER}:${TUXUMBACKUPGROUP} $i
	chmod 770 $i
done

KERNEL=`uname -r`
FUSE=`find /lib/modules/${KERNEL} -name "fuse.ko"`

if [ -n "${FUSE}" ]
then
	echo "fuse" >> /etc/modules
	modprobe fuse
fi
