#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#    LinOTP - the open source solution for two factor authentication
#    Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
#
#    This file is part of LinOTP server.
#
#    This program is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public
#    License, version 3, as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the
#               GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
#    E-mail: linotp@lsexperts.de
#    Contact: www.linotp.org
#    Support: www.lsexperts.de
#
"""
This is a monitoring program, that determines the number of used tokens.
                This script runs as a munin plugin

  Dependencies: -

"""

from sqlalchemy import *
from linotp.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()
