#!/usr/bin/python
#
# Copyright (C) 2008-2012 CS-SI. All Rights Reserved.
# Author: Sebastien Tricaud <toady@inl.fr>
#
# This file is part of the Prelude-Notify program.
#
# 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, 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.

import PreludeEasy
from PreludeEasy import ClientEasy, ConnectionPool, Connection, IDMEF
import gobject, gtk, pynotify

from PreludeNotify import ManagerConnection, notifyaction, pnstatusicon, pnconfig, threshold, x11idle, heartbeat

import sys


class Env:
        pass

env = Env()
env.gloop = gobject.MainLoop()
env.config = pnconfig.PnConfig(env)
env.notify = notifyaction.PreludeNotify(env)
env.hbmonitor = heartbeat.HeartbeatMonitor(env)
env.is_idle = False

idle = x11idle.X11Idle()
statusicon = pnstatusicon.PreludeStatusIcon(env.gloop, env.config)


def idle_timer_cb():
        idle_timeout = env.config.get("general","x11_idle_timeout")
        if idle_timeout:
                if idle.IdleTimeGet() < int(env.config.get("general","x11_idle_timeout")):
                        env.is_idle = False
                        env.notify.flush()
                        statusicon.SeenAlerts()
                else:
                        env.is_idle = True
                        statusicon.MissedAlerts()

        return True


def _expire_cb(item):
    idmef = item.idmef

    if item.count > 1:
        cstr = "%d x " % item.count
    else:
        cstr = ""

    src = cstr + (idmef.Get("alert.source(0).node.address(0).address") or "(unknown)")
    cl = idmef.Get("alert.classification.text") or "(unknown)"

    desc = idmef.Get("alert.assessment.impact.description")

    if desc:
        desc = "<b>" + cl + "</b>\n" + desc
    else:
        desc = cl

    env.notify.run(idmef.Get("alert.assessment.impact.severity"), item.messageid, src, desc)


env.expire_cb = _expire_cb

env.thresholding = threshold.Threshold(env.config.get("general","threshold_timeout"), env.expire_cb)

filter = env.config.get("idmef", "filter")
if filter != "":
        env.criteria = PreludeEasy.IDMEFCriteria(filter)
else:
        env.criteria = None

env.managercon = ManagerConnection.Session(env, env.config.get("idmef", "profile"))
for addr in env.config.get("manager","addresses").split(","):
        env.managercon.addAddress(addr)

gobject.timeout_add(1000, idle_timer_cb)
env.gloop.run()

