#!/usr/bin/python3

from __future__ import print_function

import sys, os, re

LISTEN=10
MAX_PROCS=10

fn=os.path.join(os.path.dirname(sys.argv[0]),'etc/sgconf.py')
# try to remove unsafe compiled configs
try:
  oldfn=os.path.join(os.path.dirname(sys.argv[0]),'config.py')
  os.unlink(oldfn+'c')
  os.unlink(oldfn+'o')
except:
  pass

from etc import *

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(r'^ *(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(r'(smtpd|milter)\(([\'"])',
      re.MULTILINE).sub('\\1(SCANNERS,\\2',cfg)
cfg=re.compile(r'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

# rename scanners/services
fromto=[
  ['file2stream', 'file2buffer'],
  ['stream2file', 'buffer2file'],
  ['f2s\\(', 'f2b('],
  ['s2f\\(', 'b2f('],
  ['stream2mbox', 'buffer2mbox'],
  ['restore\\(', 'cache('],
  ['store\\(', 'cache(']
]
for frm,to in fromto:
  reg1=re.compile(frm, re.M)
  if reg1.search(cfg):
    print("Renaming %s to %s." % (frm.strip('\\()'),to.strip('()')))
    cfg=reg1.sub(to,cfg)

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

# try to remove unsafe configuration
try:
  os.unlink(fn+'c')
  os.unlink(fn+'o')
except:
  pass

# moved files
if os.path.isfile('%s/tmp/status' % CHROOT) \
   and os.path.isdir('%s/var/lib/sagator' % CHROOT):
  print('Moving status file into %s/var/lib/sagator/' % CHROOT)
  try:
    os.rename('%s/tmp/status' % CHROOT,'%s/var/lib/sagator/status' % CHROOT)
  except OSError as err:
    (ec,es) = err.args
    print("Can't move: [%d] %s" % (ec,es))

if cfg==cfg_orig:
  #print "No update needed."
  sys.exit(0)
else:
  # store old config
  os.umask(0o077)
  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)
