#!/usr/bin/python

#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
# 
#  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 General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

#  Copyright (c) 2007 Ezequiel Vera


__author__ = "Ezequiel Vera"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2007 Ezequiel Vera"
__license__ = "GPL"


import curses
import traceback
import MySQLdb
import sys

sys.path.insert(1,"/usr/share/auth2db/modules/")

from configobj import ConfigObj

CONFIG_PATH = "/etc/auth2db/"
config = ConfigObj(CONFIG_PATH+'auth2db.conf')

# Carga en las variables el archivo config.dat
CONFIG_HOST = config['CONFIG_HOST']
CONFIG_DB = config['CONFIG_DB']
CONFIG_USER = config['CONFIG_USER']
CONFIG_PASS = config['CONFIG_PASS']
#CONFIG_AUTH_PATH = config['CONFIG_AUTH_PATH']


# VALIDAR CONECCION MySQLdb
try:
    conn = MySQLdb.connect (host = CONFIG_HOST,
                             user = CONFIG_USER,
                             passwd = CONFIG_PASS,
                             db = CONFIG_DB)
except MySQLdb.Error, e:
     print "Error %d: %s" % (e.args[0], e.args[1])
     sys.exit (1)


# iniciamos la pantalla

#stdscr = curses.initscr()
#curses.start_color()
#curses.noecho()
#curses.cbreak()
#stdscr.keypad(1)

class gb:
    scrn = None # will point to Curses window object
    cmdoutlines = [] # output of 'ps ax' (including the lines we don't
                     # use, for possible future extension)
    winrow = None # current row position in screen
    startrow = None # index of first row in cmdoutlines to be displayed


def show(tipo):
    gb.scrn.clear()
   # connect
    db = MySQLdb.connect(host=CONFIG_HOST, user=CONFIG_USER, passwd=CONFIG_PASS, db=CONFIG_DB)

    # create a cursor
    cursor = db.cursor()

    # execute SQL
    #sql = "SELECT fecha,pid,action,usuario,ip from login WHERE tipo = 'sshd' ORDER by fecha DESC LIMIT 0,10";
    sql = "SELECT fecha,server,tipo,pid,action,usuario,ip from login WHERE tipo = '"+str(tipo)+"' ORDER by fecha DESC LIMIT 0,20";    
    cursor.execute(sql)
    result = cursor.fetchall()
    
    separador = "------------------------------------------------------------------------------------------\n"

    #gb.scrn.addstr(separador,0)    
    gb.scrn.addstr("%-20s %10s %10s %10s %10s %10s %14s \n" % ("FECHA","SERVER","TIPO","PID","ACTION","USUARIO","IP"),0)
    gb.scrn.addstr(separador,0)
    for record in result:
        gb.scrn.addstr("%20s %10s %10s %10s %10s %10s %14s \n" % (str(record[0]),str(record[1]),str(record[2]),str(record[3]),str(record[4]),str(record[5]),str(record[6])),0) 
    
    gb.scrn.addstr(separador,0)


def main():
    # window setup
    gb.scrn = curses.initscr()
    curses.noecho()
    curses.cbreak()
    
    show("sshd")

    while True:
        # get user command
        c = gb.scrn.getch()
        c = chr(c)
        #c = stdscr.getch()
        if c == 'u': updown(-1)
        elif c == 'd': updown(1)
        elif c == 'r': show()
        elif c == '1': show('smbd')
        elif c == '2': show('login')
        elif c == '3': show('gdm')
        elif c == '4': show('sshd')
        elif c == 'k': kill()
        else: break
        
    restorescreen()

    

def restorescreen():
    curses.nocbreak()
    curses.echo()
    curses.endwin()

if __name__ =='__main__':
    try:
        main()
    except:
        restorescreen()
        # print error message re exception
        traceback.print_exc()

