#!/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/>.

quote=0
sname=""

if [ "$1" = "" -o "$2" = "" -o "$3" = "" ]; then
	echo "`basename $0` <username> <setting> <new value>"
	exit 1
fi

username=$1
setting=$2
val=$3

# 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

# Generate the path to the transmission settings file.
configfile=$userhome/.config/transmission-daemon/settings.json

# Check that it's present.
if [ "$userhome" = "" -o ! -f $configfile ]; then
	echo "Unable to find settings file for the user!"
	exit 1
fi

case $setting in
port)
	sname="rpc-port"
	;;
passwd|password)
	sname="rpc-password"
	quote=1
	;;
dldir|downloaddir)
	sname="download-dir"
	quote=1
	;;
*)
	echo "Unknown setting!"
	exit 1
	;;
esac

procs=`ps aux | grep transmission-daemon | grep -v grep`
if [ "$procs" != "" ]; then
	echo "Must stop transmission service before changing settings!"
	exit 1
fi

if [ $quote -eq 1 ]; then
	cat $configfile | sed -r "s|\"$sname\": .*,|\"$sname\": \"$val\",|g" > $configfile.tmp
else
	cat $configfile | sed -r "s|\"$sname\": .*,|\"$sname\": $val,|g" > $configfile.tmp
fi
mv $configfile.tmp $configfile
chown "$username":users $configfile

echo "Setting updated."

case $sname in
rpc-password)
	echo "NOTE: Now, start service and then stop service to scramble password."
	;;
esac

exit 0
