#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
: << =cut

=head1 NAME

transmission - Munin plugin to monitor Transmission bittorrent daemon

=head1 DESCRIPTION

This plugin implements the multigraph protocol and provides the following graphs
  transmission_throughput - monitor traffic volumes of Transmission torrents
  transmission_activity - plugin to monitor traffic speed of Transmission torrents

This plugin requires python and the transmissionrpc python module. 
See http://pypi.python.org/pypi/transmissionrpc/

=head1 CONFIGURATION

    [transmission]
        env.host 10.0.0.1
        env.port 9093
        env.user transmission
        env.pass secret

    [transmission_*]
        env.host 10.0.0.1
        env.port 9093
        env.user transmission
        env.pass secret


=head1 AUTHOR

Thomas Léveil

=head1 LICENSE

Permission to use, copy, and modify this software with or without fee
is hereby granted, provided that this entire notice is included in
all source code copies of any software which is or includes a copy or
modification of this software.

THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
PURPOSE.

=head1 CONTRIBUTE

find this plugin on github at http://github.com/VolatileMesh/munin-plugins

=head1 MAGIC MARKERS

 #%# family=auto contrib
 #%# capabilities=autoconf

=head1 VERSION

    1.1

=head1 CHANGELOG

=head2 1.0 - 2010/11/12
 
    first release

=head2 1.1 - 2011/05/29
 
    fix transmission error handling
    
=cut
"""
__version__ = '1.1'


import os, sys
from string import Template

plugin_name=list(os.path.split(sys.argv[0]))[1]
host = os.getenv('host','localhost')
port = os.getenv('port',9091)
user = os.getenv('user')
passwd = os.getenv('pass')


def config():
    conf = Template("""multigraph ${plugin_name}_throughput
graph_title Transmission throughput for ${host}
graph_vlabel bytes/${graph_period} in (-) / out (+)
graph_args --base 1000
graph_category network
graph_info This graph shows the throughput for Transmission torrents
down.label throughput
down.type COUNTER
down.draw LINE1
down.min 0
down.graph no
up.label sent
up.negative down
up.type COUNTER
up.draw LINE1
up.min 0

multigraph ${plugin_name}_activity
graph_title Transmission activity for ${host}
graph_vlabel torrents
graph_args --base 1000
graph_category network
graph_info This graph shows the number of Transmission torrents
total.label total
total.draw AREA
total.min 0
total.colour AFE3FF
active.label active
active.draw AREA
active.min 0
active.colour 77FF6F
paused.label paused
paused.draw LINE1
paused.min 0
paused.colour 8F8F8F
""")
    print conf.safe_substitute(plugin_name=plugin_name, host=host)
    sys.exit(0)


def autoconf():
    try:
        import transmissionrpc
        print('yes')
    except ImportError:
        print 'no python module \'transmissionrpc\' missing'



def fetch():
    import transmissionrpc
    
    try:
        client = transmissionrpc.Client(host, port=port, user=user, password=passwd)
    except transmissionrpc.TransmissionError, err:
        print err
        sys.exit(1)

    stats = client.session_stats(10)
    print_values_throughput(stats)
    print_values_activity(stats)
	
	
def print_values_activity(stats):
    print "multigraph {plugin_name}_activity".format(plugin_name=plugin_name)
    try:
        print "total.value %s" % stats.torrentCount
    except:
        print "total.value U"
        
    try:
        print "active.value %s" % stats.activeTorrentCount
    except:
        print "active.value U"
		
    try:
        print "paused.value %s" % stats.pausedTorrentCount
    except:
        print "paused.value U"


def print_values_throughput(stats):
    print "multigraph {plugin_name}_throughput".format(plugin_name=plugin_name)
    try:
        print "down.value %s" % stats.cumulative_stats['downloadedBytes']
    except:
        print "down.value U"
        
    try:
        print "up.value %s" % stats.cumulative_stats['uploadedBytes']
    except:
        print "up.value U"
    


def dumpstats():
    import transmissionrpc
    try:
        client = transmissionrpc.Client(host, port=port, user=user, password=passwd)
    except transmissionrpc.transmission.TransmissionError, err:
        print err
        sys.exit(1)
    stats = client.session_stats(10)
    print stats

    
if __name__ == '__main__':
    if len(sys.argv)>1 :
        if sys.argv[1]=="dumpstats" :
			dumpstats()
        elif sys.argv[1]=="config" :
            config()
        elif sys.argv[1]=="autoconf" :
            autoconf()
        elif sys.argv[1]!="":
            raise ValueError, "unknown parameter '%s'" % sys.argv[1]

fetch()
sys.exit(0)
