#!/bin/sh
# Copyright 2009 Saravana Kannan
# <sarav dot devel [ignore this] at gmail period com>
#
# This file is part of syno-packager.
#
# syno-packager is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# syno-packager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with syno-packager.  If not, see <http://www.gnu.org/licenses/>.

delsettings=0
userlist=/usr/local/etc/transmission.users

if [ "$1" = "-f" ]; then
	shift
	delsettings=1
fi

if [ "$1" = "" ]; then
	echo "`basename $0` [-f] <username>"
	echo "Delete user from list of allowed transmission users."
	echo "Option -f deletes all transmission config files of th user."
	exit 1
fi

username=$1

grep "^$username$" $userlist 1>/dev/null 2>/dev/null
if [ $? -ne 0 -a $delsettings -eq 0 ]; then
	echo "Not an existing transmission user."
	exit 1
fi

# Delete the user from the user list.
grep -v "^$username$" $userlist 1>$userlist.tmp 2>/dev/null
mv $userlist.tmp $userlist

# Nothing more to do if settings are not to be deleted.
if [ $delsettings -eq 0 ]; then
	exit 0
fi

# Find the path to the user's home dir.
userhome=`su "$username" -s /bin/sh -c "echo \\$HOME"`
if [ $? -ne 0 ]; then
	echo "Invalid user name $username !"
	exit 1
fi

# Check that it's present.
if [ "$userhome" = "" -o ! -d "$userhome" ]; then
	echo "User $username has no home directory! Nothing to delete!"
	exit 1
fi

# Delete transmission settings.
rm -rf $userhome/.config/transmission-daemon
rmdir $userhome/.config 2>/dev/null
rmdir $userhome/transmission 2>/dev/null
