// deleted/main.cc
// This file is part of Decimail; see http://decimail.org
// (C) 2004 Philip Endecott
 
// This is version $Name$
//   (if there is no version (e.g. V0-1) mentioned in the previous line,
//    this is probably a snapshot from between "official" releases.)
 
// 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
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


#include "DmDatabase.hh"

#include "select.hh"

#include <syslog.h>


static void delete_message(int msg_id)
{
  assert(msg_id<1000000);
  char numstr[7];
  sprintf(numstr,"%06d",msg_id);
  string fn = "/var/local/decimail/messages/";
  fn += numstr[0];
  fn += numstr[1];
  fn += "/";
  fn += numstr[2];
  fn += numstr[3];
  fn += "/";
  fn += numstr[4];
  fn += numstr[5];

  syslog(LOG_INFO,"Deleting %s",fn.c_str());
  int rc = unlink(fn.c_str());
  if (rc) {
    throw SysException("unlink("+fn+")");
  }
}


static void wait_for_any_pending(DmDatabase& db)
{
  while (1) {
    if (select_rt(db.get_fd(),1000.0)==-1) {
      return;
    }
    string n = db.get_any_notification();
    if (n=="delete_log") {
      return;
    }
  }
}


static void delete_any_pending(DmDatabase& db)
{
  DmDatabase::Transaction t(&db);

  DmDatabase::Query q(&db);
  q << "select msg_id from delete_log for update;";
  q.run();

  for (int i=0; i<q.get_ntuples(); ++i) {

    int m = q.get_num(i,0);

    delete_message(m);
    DmDatabase::Query d(&db);
    d << "delete from delete_log where msg_id=" << m << ";";
    d.run();
    
  }

  t.commit();
}



int main(int argc, char* argv[])
{
  try { try {
  
    openlog("dmdeleted",LOG_PID,LOG_MAIL);
    syslog(LOG_INFO,"Decimail deleted starting");

    DmDatabase db;

    DmDatabase::Query l(&db);
    l << "listen delete_log;";
    l.run();
    
    while(1) {
      delete_any_pending(db);
      wait_for_any_pending(db);
    }

  } RETHROW_MISC_EXCEPTIONS }
  catch (Exception& E) {
    ostringstream err_msg;
    E.report(err_msg);
    syslog(LOG_CRIT,"Decimail deleted failed: %s",err_msg.str().c_str());
    exit(1);
  }
}
