#!/usr/bin/env python
# -*- coding: utf-8 -*-
#   WillowNG - Content Filtering Web Proxy 
#   Copyright (C) 2006  Travis Watkins
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Library General Public
#   License as published by the Free Software Foundation; either
#   version 2 of the License, or (at your option) any later version.
#
#   This library 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
#   Library General Public License for more details.
#
#   You should have received a copy of the GNU Library General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import gobject
import os
import sys
import dl
from pysqlite2 import dbapi2 as sqlite
from WillowNG.proxy import ForkingHTTPProxy
from WillowNG import domain, bayesian, util, daemonize

try:
	from WillowNG import config
	datadir = config.pkgdatadir
	confdir = config.confdir
except:
	datadir = '.'
	confdir = '.'

#fork off into a non-attached daemon
daemonize.createDaemon()

#change process listing and killall to 'willowng'
libc = dl.open('/lib/libc.so.6')
libc.call('prctl', 15, 'willowng\0', 0, 0, 0)
sys.argv[0] = 'willowng'

db_list = sqlite.connect(os.path.join(datadir, 'builtin.db')), sqlite.connect(os.path.join(confdir, 'training.db'))
util.setupTables(db_list[1])
bayes = bayesian.Bayes(db_list)
domain_filter = domain.DomainFilter(db_list)

#if dbus is installed start the interface, otherwise just forget it
try:
	from WillowNG import dbusinterface
	dbusinterface.interface.bayes = bayes
	dbusinterface.interface.domain = domain_filter
except:
	pass

config = util.readConfig(confdir, datadir)
proxy = ForkingHTTPProxy(('', 8563), bayes, domain_filter, config)
mainloop = gobject.MainLoop()
gobject.idle_add(proxy.serve_forever)
mainloop.run()
