#! /usr/bin/env python

import psycopg2
import os
import json

pgconn = psycopg2.connect(
        database=os.environ.get('DATABASE_NAME'),
        user=os.environ.get('DATABASE_USER'),
        password=os.environ.get('DATABASE_PASSWORD'),
        host=os.environ.get('DATABASE_HOST'))
cur = pgconn.cursor()

result = {}

cur.execute('SELECT COUNT(*) FROM auth_user')
result['users_count'] = cur.fetchone()[0]

cur.execute("""select count(*) from auth_user
                where last_login > (current_timestamp - interval '1 day')""")
result['users_last_connection_less_than_one_day_ago'] = cur.fetchone()[0]

cur.execute("""select count(*) from auth_user
                where last_login > (current_timestamp - interval '1 hour')""")
result['users_last_connection_less_than_one_hour_ago'] = cur.fetchone()[0]

cur.execute("""select count(*) from saml_libertyfederation
                where sp_id IS NOT NULL""")
result['active_federations'] = cur.fetchone()[0]

cur.execute("""select saml_libertyprovider.slug, count(*) from saml_libertyfederation, saml_libertyprovider
                where saml_libertyprovider.id = saml_libertyfederation.sp_id
             group by saml_libertyprovider.slug""")
while True:
    row = cur.fetchone()
    if not row:
        break
    result['%s_active_federations' % row[0]] = row[1]

print json.dumps(result)
