#!/usr/bin/python2.3

'''Sagator Back from Quarantine script.
 
This program can be used to requeue an quarantined mail from
quarantine to queue/user mailbox.
 
(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.

Usage:
  sqback [--to RCPT] quarantined_file1 [quarantined_files...]
'''

import sys,socket,re
from default import SMTP_SERVER
from config import SMTP_SERVER

def showhelp():
    print "sqback usage:"
    print "  sqback [--to RCPT] quarantined_file1 [quarantined_files...]"
    sys.exit()

rcptto=''
args=[]
n=1
while n<len(sys.argv):
  if sys.argv[n]=='--to':
    rcptto=sys.argv[n+1]
    n+=2
    continue
  if sys.argv[n][:2]=='--':
    print "Unknown parameter:",sys.argv[n]
    showhelp()
  else:
    args.append(sys.argv[n])
    n+=1

if len(args)==0:
  showhelp()

try:
  for fname in args:
    conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    conn.connect(SMTP_SERVER)
    print "Connection to: "+str(SMTP_SERVER)+" established"
    f=open(fname,'r')
    r_rcptto=re.compile("^RCPT TO:.*[\r]*$",re.IGNORECASE|re.MULTILINE)
    r_data=re.compile("^DATA[\r]*$",re.IGNORECASE|re.MULTILINE)
    if rcptto:
      buf=f.read()
      buf=r_rcptto.sub("RCPT TO: "+rcptto,buf,1)
      while 1:
        e=r_rcptto.search(buf).end()
        s=r_data.search(buf).start()
        while buf[e] in ['\r','\n']:
          e+=1
        if e<s:
          buf=buf[:e]+buf[s:]
        else:
          break
      conn.sendall(buf)
    else:
      conn.sendall(f.read())
    f.close()
    while 1:
      try:
        r=conn.recv(10240)
        if r=='': break
        print r.strip()
      except:
        print "Connection closed."
        break
except IOError,(ec,es):
  print "IOError:", es+":" , fname
