#!/bin/sh

shell_user="utorrent"
uts_path=/usr/local/utorrent
bin_path=${uts_path}/bin
uts_bin=${bin_path}/utserver
lib_path=${uts_path}/lib64
uts_ld=${bin_path}/utorrent
pid_file=${uts_path}/pid/utserver.pid
settings_path=${uts_path}/settings
config_file=${uts_path}/conf/utserver.conf
log_file=${uts_path}/log/ut.log
PATH=${bin_path}:$PATH

# Locales:
# C POSIX cs_CZ.utf8 da_DK.utf8 de_DE.utf8 en_US.utf8 es_ES.utf8 fr_FR.utf8 hu_HU.utf8 it_IT.utf8 ja_JP.utf8 ko_KR.utf8
# nb_NO.utf8 nl_NL.utf8 pl_PL.utf8 pt_BR.utf8 pt_PT.utf8 ru_RU.utf8 sv_SE.utf8 tr_TR.utf8 zh_CN.utf8 zh_TW.utf8

LANG=ru_RU.utf8
local PREFIX=${uts_path}
export LANG
LC_ALL=$LANG
export LC_ALL
export PATH

case "$1" in
  start)
	if [ -s "$pid_file" ]
	then
		kill -s 0 `cat $pid_file` > /dev/null 2>&1
		if  [ "$?" == "0" ]
		then
			echo "Err: Utorrent seems to be running, PID `cat $pid_file`"
			exit 1
		fi
	fi
		echo "Starting Utorrent Server.."
#		su -c "cd $settings_path; $uts_ld --library-path $lib_path $uts_bin -settingspath $settings_path -configfile $config_file -logfile $log_file -pidfile $pid_file -daemon" $shell_user
		su -c "cd $uts_path; $uts_ld --library-path $lib_path $uts_bin -settingspath $settings_path -configfile $config_file -logfile $log_file -pidfile $pid_file -daemon" $shell_user
	;;
  stop)
	if [ -s "$pid_file" ]
	then
		kill -s 0 `cat $pid_file` > /dev/null 2>&1
		if  [ "$?" == "0" ]
		then
			echo "Stopping Utorrent Server.."
			kill `cat $pid_file`
			tail -f /dev/null --pid `cat $pid_file`
			rm -f $pid_file
		else
			echo "Err: Utorrent seems to be stopped, PID file $pid_file not found or empty"
		fi
	else
		echo "Err: Utorrent seems to be stopped, PID file $pid_file not found or empty"
	fi
	;;
  restart)
	$0 stop ; sleep 1 ; $0 start || exit 1
	;;
  status)
	if [ -s "$pid_file" ]
	then
		kill -s 0 `cat $pid_file` > /dev/null 2>&1
		if  [ "$?" == "0" ]
		then
			echo "Utorrent seems to be running, PID `cat $pid_file`"
		else
			echo "PID file present, but no process with PID `cat $pid_file` running"
		fi
	else
		echo "Utorrent seems to be stopped, PID file $pid_file not found or empty"
	fi
	;;
  *)
	echo "Usage $0 {start|stop|reload|status}"
	;;
  log)
	echo ${log_file} ; exit 0
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|status|log}" >&2
	exit 1
	;;
esac

exit 0
