
#include <string>
#include "EPoll.h"
#include "ConsoleServer.h"
#include "Exception.h"
#include "File.h"
#include "Log.h"
#include "IPAddress.h"
#include "MailFileSystem.h"
#include "SMTPServer.h"
#include "POP3Server.h"
#include "IMAPServer.h"
#include "SendMail2.h"

#define BUFFER_SIZE 1000000

int main(int argc, char **argv) {
   coreutils::Log(new coreutils::File("/var/log/barantmail.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
   coreutils::Log(coreutils::LOG_INFO) << "BMAMAIL called with link " << argv[0];
   if(strcmp(argv[0], "./sendmail2") == 0) {
      try {
         coreutils::Log(coreutils::LOG_INFO) << "Starting Mail Injector. Build " << __DATE__ << " " << __TIME__;
	 char buffer[BUFFER_SIZE];
	 int len = read(0, buffer, BUFFER_SIZE);
         core::EPoll ePoll;
         mail::SendMail2(ePoll, argv[1], argv[2]);
      }
      catch(coreutils::Exception exception) {
         std::cout << exception.text << " Error reason is '" << strerror(exception.errorNumber) << "' in file " << exception.file << " at line " << exception.line << std::endl;
      }
   } else {

   try {

      coreutils::Log(coreutils::LOG_INFO) << "BMAMail Server starting. Build " << __DATE__ << " " << __TIME__;

      std::string hostName = "localhost";
      std::string ipAddress = "0.0.0.0";
      coreutils::ZString mailPath("/var/mail");

      mail::MailFileSystem mailFileSystem(mailPath);

      core::EPoll ePoll;
      ePoll.start(1, 1000);
      mail::SMTPServer smtpServer(ePoll, hostName, mailFileSystem, core::IPAddress(ipAddress, 9025));
//      mail::POP3Server pop3Server(ePoll, hostName, mailFileSystem, core::IPAddress(ipAddress, 110));
//      mail::IMAPServer imapServer(ePoll, hostName, mailFileSystem, core::IPAddress(ipAddress, 143));
      core::ConsoleServer consoleServer(ePoll, core::IPAddress(ipAddress, 1027));
      consoleServer.commands.add(consoleServer.commands, "help");
      consoleServer.commands.add(smtpServer.commands, "smtp");

      while(true)
        sleep(3600);

      ePoll.stop();

   }

   catch(coreutils::Exception exception) {
      std::cout << exception.text << " Error reason is '" << strerror(exception.errorNumber) << "' in file " << exception.file << " at line " << exception.line << std::endl;
   }
   }
}
