#!/usr/local/bin/python
# 
# Wireless Leiden webinterface for (embedded) nodes
# Rick van der Zwet <info@rickvanderzwet.nl>
import cherrypy
from cherrypy.process.plugins import Daemonizer, PIDFile

# Assisting non-cherrypy stuff
from subprocess import *
import os
import getopt
import sys

def tailFile(file):
  lines=-10
  return("<em>Tail (%i): %s</em><br /><pre>%s</pre>" % (lines,file,Popen(["tail", str(lines), file], stdout=PIPE).communicate()[0]));

def catFile(file):
  return("<em>File: %s</em><br /><pre>%s</pre>" % (file,Popen(["cat", file], stdout=PIPE).communicate()[0]));

def allRoutes():
  return("<em>netstat -nr</em><br /><pre>%s</pre>" % Popen(["netstat", "-n", "-r"], stdout=PIPE).communicate()[0]);

def processList():
  return("<em>ps -aux</em><br /><pre>%s</pre>" % Popen(["ps", "-a", "-u", "-x"], stdout=PIPE).communicate()[0]);

class OnePage(object):
  def index(self):
    return "one page!"
  index.exposed = True

class HelloWorld(object):
    onepage = OnePage()
    def index(self):
        return ( "<img src='/static/wl-logo.png' />" +
	"Welcome to <a href='http://www.wirelessleiden.nl'>Stichting Wireless Leiden</a> host/node <em>" +
        Popen(["hostname"], stdout=PIPE).communicate()[0]  +
        "</em><p />" + tailFile('/var/log/messages') + "<p />" +
         tailFile('/var/log/debug.log') + "<p />" +
         catFile('/var/run/dmesg.boot') + "<p />" +
         processList() + "<p />" +
	 allRoutes() + "<p />" +
	 "<em>$Id$</em>")
    index.exposed = True

    def doLogin(self, username=None, password=None):
       return '1' # check the username & password
    doLogin.exposed = True

def usage():
  sys.stderr.write("""Usage: %s [-dfg] [-c <file>]
	[-c|--cfg] <file>	configuration file to use, instead of default cherrypy3.cfg
	[-d|--daemonize]	daemonize webserver
	[-f|--foreground]	Stick to foreground
  [-g|--development] Debug mode = foreground and all logs to screen
  """ % __file__)


# Should soon be ported to some magic cherryd daemon which offers the same
# functionality http://www.cherrypy.org/wiki/WhatsNewIn31
if __name__ == '__main__':
  try:
    opts, args = getopt.getopt(sys.argv[1:], "c:dgfp:", ["cfg=", "daemonize", "development",
                   "foreground", "pidfile="]) 
  except getopt.GetoptError:
    usage()
    sys.exit(2)

  # defaults
  current_dir = os.path.dirname(os.path.abspath(__file__))
  configfile = '%s/cherrypy3.cfg' % os.path.dirname(os.path.abspath(__file__))

  opt_daemonize= None
  opt_development = None
  opt_pidfile = None
  opt_foreground = None
  opt_debug = None

  for  opt, arg in opts:
    if opt in ('-c', '--cfg'):
      configfile = arg
    elif opt in ('-d', "--daemonize"):
      opt_daemonize= True
    elif opt in ('-g', "--development"):
      opt_development = True
    elif opt in ('-f', "--foreground"):
      opt_foreground = True
    elif opt in ('-p', "--pidfile"):
      opt_pidfile = arg

  # Parse config file    
  cherrypy.config.update(configfile)

  # Set options
  if opt_development:
    opt_daemonize = None
    opt_foreground = True
    opt_pidfile = None
    cherrypy.config.update( { 'log.error_file' : None, 
                              'log.access_file' : None,
                              'log.screen' : True,
                            })
  if opt_daemonize:
    cherrypy.config.update({'daemonize' : True})
  if opt_foreground:
    cherrypy.config.update({'daemonize' : False})
  if opt_pidfile:
    cherrypy.config.update({'pidfile' : opt_pidfile})

  # Send to background if needed
  if cherrypy.config.get('daemonize'):
    d = Daemonizer(cherrypy.engine)
    d.subscribe()

  # Record pid if defined
  pidfile = cherrypy.config.get('pidfile')
  if pidfile:
    PIDFile(cherrypy.engine, pidfile).subscribe()

  # Start your engines!
  cherrypy.quickstart(HelloWorld(),config=configfile)