#!/usr/bin/python

import sys,os,re
LISTEN=10
MAX_PROCS=10
from default import *
from config import *

fn=os.path.join(os.path.dirname(sys.argv[0]),'config.py')
cfg=open(fn,'r').read()
cfg_orig=cfg

# add SRV[] array
if SRV==[]:
  out=""
  out+="from srv import *\n";
  out+="SRV=[\n"
  out+="  # statistics collector\n"
  try:
    out+="  collector('"+COLLECTOR_SERVER[0]+\
         "', "+str(COLLECTOR_SERVER[1])+"),\n"
  except NameError:
    out+="  #collector('0.0.0.0',28),\n"
  out+="  # SMTP daemon (for posfix etc.)\n"
  try:
    out+="  smtpd(SCANNERS,'"+BIND_ADDR[0]+"', "+str(BIND_ADDR[1])+")\n"
  except (NameError,TypeError):
    out+="  #smtpd(SCANNERS,'127.0.0.1',27)\n"
  out+="  # Milter daemon\n"
  try:
    out+="  milter(SCANNERS,'"+MILTER[0]+"', "+MILTER[1]+")\n"
  except (NameError,TypeError):
    out+='  #milter(SCANNERS,"sagator","inet:3333@127.0.0.1")\n'
  out+="  # Filte\n  #avfilter(SCANNERS)\n"
  out+="]\n"
  print "Updating %s by:" % fn
  print out
  cfg+="\n"+out

# remove LISTEN, MAX_PROCS, BIND_ADDR, ...
cfg0=cfg
cfg=re.compile('^ *(LISTEN|MAX_PROCS|BIND_ADDR|COLLECTOR_SERVER) *=.*?$\n',re.MULTILINE
      ).sub('',cfg)
if cfg0!=cfg:
  print "Removing obsolete parameters."

# update from 0.5.3-rc7 to 0.5.3-rc8
cfg0=cfg
cfg=re.compile('(smtpd|milter)\(([\'"])',
      re.MULTILINE).sub('\\1(SCANNERS,\\2',cfg)
cfg=re.compile('avfilter\(\)',
      re.MULTILINE).sub('avfilter(SCANNERS)',cfg)
if cfg0!=cfg:
  print "Updating SERVICES for new syntax."
reg_srv=re.search('^ *SRV[ \n]*=[ \n]*\[.*?^ *\]',cfg,re.M|re.DOTALL)
reg_sca=re.search('^ *SCANNERS[ \n]*=[ \n]*\[.*?^ *\]',cfg,re.M|re.DOTALL)
try:
  if reg_srv.start()<reg_sca.start():
    cfg=cfg[:reg_srv.start()] + '\n' \
       +cfg[reg_sca.start():] + '\n' \
       +cfg[reg_srv.start():reg_srv.end()]
    print "Moving SRV array after SCANNERS (SRV uses SCANNERS)."
except:
  pass # update not required, at least one array not defined

if len(sys.argv)>1:
  print cfg
  sys.exit(1)

if cfg==cfg_orig:
  #print "No update needed."
  sys.exit(0)
else:
  # store old config
  open(fn+'.sagatorsave','w').write(cfg_orig)
  print 'Your old configuration is saved into "%s".' % (fn+'.sagatorsave')
  # save, close and rename file
  open(fn,'w').write(cfg)
