#!/usr/bin/python

'''
sagator.py
(c) 2003-2004 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 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.

'''

from aglib import *
import signal,time
import avlib

# load config
from default import *
try:
  from config import *
except ImportError,es:
  if str(es)[-6:]=="config":
    print "ERROR! Config file not found! Exiting now."
    sys.exit(1)
  else:
    raise

if __name__ == '__main__':
  debug.set_level(DEBUG_LEVEL)
  n=1
  while n<len(sys.argv):
    if sys.argv[n]=='--help':
      print "SAGATOR",SG_VER_REL
      print "(c) Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>"
      print "Licensed under GNU GPL."
      print ""
      print "Params: --help        this help"
      print "        --config f    load \"f\" as alternate config (without .py extension)"
      print "        --nodaemon    don't daemonize after startup"
      print "        --logfile l   filename for logging ('-' for stdout)"
      print "        --debug l     set debug level to l"
      sys.exit(0)
    elif sys.argv[n]=='--config':
      try:
        exec("from %s import *" % sys.argv[n+1])
      except ImportError,es:
        print "ImportError:",es
      n+=2
    elif sys.argv[n]=='--daemon':
      globals.daemon=True
      n+=1
    elif sys.argv[n] in ('--nodaemon','-n'):
      globals.daemon=False
      n+=1
    elif sys.argv[n]=='--logfile':
      LOGFILE=sys.argv[n+1]
      n+=2
    elif sys.argv[n]=='--debug':
      debug.set_level(int(sys.argv[n+1]))
      n+=2
    else:
      print "Unknown parameter:", sys.argv[n]
      sys.exit(1)
  debug.set_logfile(LOGFILE)
  debug.chroot=CHROOT
  globals.USER=USER
  globals.GROUP=GROUP
  globals.CHROOT=CHROOT
  globals.pid_file=PID_FILE
  avlib.smtp.SMTP_SERVER=SMTP_SERVER
  signal.signal(signal.SIGUSR2,sigusr2)
  if globals.daemon:
    os.close(0) # close stdin
  debug.echo(1,"SAGATOR %s starting at %s" \
    % (SG_VER_REL,time.strftime("%c",time.localtime())))
  try:
    # open PID file
    try:
      if globals.daemon:
        globals.pidf=open(globals.pid_file,'w')
    except:
      if globals.pid_file:
        debug.echo(0,"Can't open pid file: ",globals.pid_file)
    # start services
    for service in SRV:
      pids=service.main()
      globals.service_pids.extend(pids)
    for pid in globals.service_pids:
      if globals.daemon:
        globals.pidf.write(str(pid)+" ")
    debug.echo(6,"Services finished, pids: ",str(globals.service_pids))
    if not globals.daemon:
      while True:
        time.sleep(60)
  except KeyboardInterrupt:
    sigterm('KeyboardInterrupt') # kill self
