#!/usr/bin/python
# -*- coding: utf-8 -*-
'''

  product:  LinOTP2
  module:   LinOTP server
  tool:     linotp-tokens-used
  edition:  Enterprise Edition
  
  Copyright (C) 2010 - 2013 LSE Leading Security Experts GmbH
  License:  LSE Leading Security Experts GmbH
  contact:  http://www.linotp.org
            http://www.lsexperts.de
            linotp@lsexperts.de

  Description:  This is a monitoring program, that determines the number of used tokens.
                This script runs as a munin plugin
                
  Dependencies: -
  
'''
from sqlalchemy import *
from linotpee.lib.utils import config_get, INI_FILE
import sys

def tokens_used(SQL_URL):
    '''
    Return the overall token number in the database
    '''
    id_pos = 0
    
    engine = create_engine(SQL_URL)
       
    engine.echo = False  # We want to see the SQL we're creating
    metadata = MetaData(engine)

    # The audit table already exists, so no need to redefine it. Just
    # load it from the database using the "autoload" feature.
    token = Table('Token', metadata, autoload=True)

    overall_number = 0
    not_assigned = 0
    not_active = 0
    
    # overall
    rows = token.count().execute()
    row =  rows.fetchone()
    overall_number = int( row[id_pos] )
    
    # not assigned tokens
    rows = token.count().where("LinOtpUserid=''").execute()
    row = rows.fetchone()
    not_assigned = int( row[id_pos] )
    
    # disabled tokens
    rows = token.count().where("LinOtpIsactive=0").execute()
    row = rows.fetchone()
    not_active = int( row[id_pos] )
    
    return (overall_number, not_active, not_assigned)

def print_config():
    '''
    Print the munin config
    '''
    print 'graph_title LinOTP Tokens'
    print 'graph_vlabel Tokens'
    print '_tokennum.label token count'
    print '_inactive.label inactive tokens'
    print '_notassigned.label not assigned tokens'
    
    
def main():
    
    SQL_URL  = config_get("app:main", "sqlalchemy.url")
    
    if len(sys.argv) == 2:
        if sys.argv[1] == "config":
            print_config()
        else:
            print "invalid argument"
    elif len(sys.argv) == 1:
        (t, n_active, n_assigned) = tokens_used(SQL_URL)
        print "_tokennum.value %i" % t
        print "_inactive.value %i" % n_active
        print "_notassigned.value %i" % n_assigned
    else:
        print "wrong number of arguments"
        
    sys.exit(0)

if __name__ == '__main__':
    main()
