#!/bin/sh
IFCONFIG="/sbin/ifconfig"
BONDINTERFACE="bond0"
INTERFACEA="egiga0"
INTERFACEB="egiga1"
CONFIG_FOLDER="/usr/local/zy-pkgs/config/Transmission"
STATUS_FILE=${CONFIG_FOLDER}/Transmission
TransmissionExe=/usr/local/zy-pkgs/bin/transmission-daemon
DEFAULT_CONF=/usr/local/zy-pkgs/gui/Transmission/transmission/web/settings.json
TransmissionConf=${CONFIG_FOLDER}/settings.json
CONTROLFILE="/usr/local/zy-pkgs/zypkg_conf/info/Transmission.control"
export LD_LIBRARY_PATH=/usr/local/zy-pkgs/lib
export TRANSMISSION_WEB_HOME=/usr/local/zy-pkgs/gui/Transmission/transmission/web/

enable(){
	$TransmissionExe -g /usr/local/zy-pkgs/config/Transmission/
}

disable(){
	killall transmission-daemon
	/usr/sbin/lro_switch.sh tsmission lro_on
}
if [ "$1" == "getlink" ]; then
	BOND0=`${IFCONFIG} ${BONDINTERFACE} | grep "inet addr" | tr -s ' '`
	if [ "${BOND0}" == "" ]; then
		ADDR0=`${IFCONFIG} ${INTERFACEA} | grep "inet addr" | tr -s ' '`
		if [ "${ADDR0}" == "" ]; then
			ADDR1=`${IFCONFIG} ${INTERFACEB} | grep "inet addr" | tr -s ' '`
			echo  "http://`echo ${ADDR1} | cut -d ' ' -f 2 | cut -d ':' -f 2`:`sed -n '/"rpc-port"/p' /usr/local/zy-pkgs/config/Transmission/settings.json | awk -F'[:,]' '{print $2}' | cut -d ' ' -f 2`"
		else
			echo  "http://`echo ${ADDR0} | cut -d ' ' -f 2 | cut -d ':' -f 2`:`sed -n '/"rpc-port"/p' /usr/local/zy-pkgs/config/Transmission/settings.json | awk -F'[:,]' '{print $2}' | cut -d ' ' -f 2`"
		fi
	else	
		echo  "http://`echo ${BOND0} | cut -d ' ' -f 2 | cut -d ':' -f 2`:`sed -n '/"rpc-port"/p' /usr/local/zy-pkgs/config/Transmission/settings.json | awk -F'[:,]' '{print $2}' | cut -d ' ' -f 2`"
	fi
		
elif [ "$1" == "enable" ]; then
	enable
	echo "Enabled" > $STATUS_FILE
elif [ "$1" == "disable" ]; then
	disable
	echo "Disabled" > $STATUS_FILE
elif [ "$1" == "status" ]; then
	if [ -f $STATUS_FILE ]; then
		echo `cat $STATUS_FILE`
	else
		mkdir -p ${CONFIG_FOLDER}
		echo "Disabled" > $STATUS_FILE
		echo `cat $STATUS_FILE`
	fi
elif [ "$1" == "startup" ]; then
	#check UPnP database
	UPNPCOUNT=`sqlite3 /etc/zyxel/upnp.db "SELECT COUNT(*) FROM upnpInfo WHERE service='TRANSMISSION'"`
	if [ 0 == $UPNPCOUNT ]; then
		/usr/local/upnp/install_upnpDB.sh TRANSMISSION 9091 'http://ip:port' 'This package is another P2P download client which supports torrent and magnet.'
	fi
	if [ ! -e $CONFIG_FOLDER ]; then
		mkdir -p ${CONFIG_FOLDER}
	fi
	if [ ! -f $TransmissionConf ]; then
		/bin/cp $DEFAULT_CONF $CONFIG_FOLDER
	fi

	STATUS=`cat $STATUS_FILE`
	if [ "$STATUS" == "Enabled" ]; then
		enable
	else
		disable
	fi
elif [ "$1" == "shutdown" ]; then
	disable
elif [ "$1" == "version" ]; then
	VERSION=`grep "Version:" ${CONTROLFILE} | awk -F"zypkg" '{print $2}'`
	return ${VERSION}
fi
exit 0
