#!/bin/sh

##############################################################################
#
# Copyright 2010 ClearFoundation
#
##############################################################################
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
###############################################################################

# A quick script to set a password for Transmission

DAEMON_USER="transmission"
TRANSMISSION_USERDIR=`getent passwd $DAEMON_USER | cut -d: -f6`
TRANSMISSION_HOME="$TRANSMISSION_USERDIR/.config/transmission-daemon"
RUNNING_UPDATE="/var/clearos/transmission/running_update"

OLDCONFIG="$TRANSMISSION_USERDIR/settings.json"
CONFIG="$TRANSMISSION_HOME/settings.json"
ISRUNNING=`/sbin/pidof transmission-daemon`
ISNEW=""

if [ -z "$1" ]; then
	echo "Usage: $0 password"
	exit 1
fi

touch $RUNNING_UPDATE

if [ ! -e "$CONFIG" ]; then
    ISNEW="yes"
	service transmission-daemon start >/dev/null 2>&1
	sleep 5
    if [ -e "$OLDCONFIG" ]; then
        echo "Warning old config found at $OLDCONFIG"
        echo "Please check for configuration changes and restart the daemon"
        echo "(The old config can be removed)"
	fi
	echo "Daemon generated new config at $CONFIG"
fi

service transmission-daemon stop >/dev/null 2>&1
sleep 3

if [ -e "$CONFIG" ]; then
	sed -i -e "s/^[[:space:]]*\"rpc-password\".*/    \"rpc-password\": \"$1\", /" $CONFIG
	sed -i -e "s/^[[:space:]]*\"rpc-username\".*/    \"rpc-username\": \"admin\", /" $CONFIG
	sed -i -e "s/^[[:space:]]*\"rpc-whitelist-enabled\".*/    \"rpc-whitelist-enabled\": false, /" $CONFIG
	sed -i -e "s/^[[:space:]]*\"rpc-authentication-required\".*/    \"rpc-authentication-required\": true, /" $CONFIG
	echo "New password set in config $CONFIG"
else
	echo "Oops. Automatic creation of config file has failed, please review your transmission installation"
    rm -f $RUNNING_UPDATE
	exit 0
fi

if ( [ -n "$ISRUNNING" ] || [ -n "$ISNEW" ] ); then
	service transmission-daemon start >/dev/null 2>&1
fi

rm -f $RUNNING_UPDATE
