#!/bin/sh

FILE='/tmp/mc_player_count'
LOG='/home/minecraft/rtorrent_bandwidth/log'
SOCKET='/home/rtorrenter/session/rpc.socket'

check_file() {
	if [ ! -e "$FILE" ]; then
		echo "rtorrent_bandwidth: $FILE not found!" >&2
		exit 1
	fi
}

log() {
	printf '%s: %s\n' "$(date '+%F %R')" "$1" >> "$LOG"
}


case "$1" in
	'init')
		echo 0 > "$FILE"
		log "=== SCRIPT INIT ==="
		;;
	'join')
		check_file
		echo $(($(cat "$FILE") + 1)) >"$FILE"
		log "player join"
		;;
	'quit')
		check_file
		echo $(($(cat "$FILE") - 1)) >"$FILE"
		log "player quit"
		;;
	*)
		echo "$0: unrecognized option $1" >&2
		exit 1
		;;
esac



if [ $(cat "$FILE") -gt 0 ]; then
	/usr/bin/xmlrpc2scgi -p "$SOCKET" "throttle.global_up.max_rate.set" "" "2097152"
	log "$(cat $FILE) players online, throttling upload rate"
else
	/usr/bin/xmlrpc2scgi -p "$SOCKET" "throttle.global_up.max_rate.set" "" "0" # unlimited
	log "$(cat $FILE) players online, lifting upload rate throttle"
fi
