#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include "globals.h"
#include "sendmail.h"

int
sm_writeln (int sockfd, char *line)
{
  int len = strlen (line);

  write (sockfd, line, len);
  return 0;
}

int
sm_sendmail (char *smtp, char *odkogo, char *dokogo, char *temat, char *tresc)
{
  int sockfd, k;
  struct sockaddr_in serv_addr;
  char bigbuf[2000];

  bzero ((char *) &serv_addr, sizeof (serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = inet_addr (smtp);
  serv_addr.sin_port = htons (25);

  if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
    {
      // no socket
      return 0;
    }


  if (connect (sockfd, (struct sockaddr *) &serv_addr, 
sizeof (serv_addr)) <
      0)
    {
      
	//no smtp
	return 0;
    }

//wysylanko
// todo sprawdzic czy out jest poprawne
  k = read (sockfd, bigbuf, 1999);
  printf ("Mail wysylanko: %s %s\n", dokogo, temat);
  snprintf (bigbuf, sizeof (bigbuf), "helo localhost\n");
  sm_writeln (sockfd, bigbuf);
  k = read (sockfd, bigbuf, 1999);	//ehlo
  snprintf (bigbuf, sizeof (bigbuf), "mail from: %s\n", odkogo);
  sm_writeln (sockfd, bigbuf);
  k = read (sockfd, bigbuf, 1999);	//ok
  snprintf (bigbuf, sizeof (bigbuf), "rcpt to: %s\n", dokogo);
  sm_writeln (sockfd, bigbuf);
  k = read (sockfd, bigbuf, 1999);	//ok
  snprintf (bigbuf, sizeof (bigbuf), "data\n");
  sm_writeln (sockfd, bigbuf);
  k = read (sockfd, bigbuf, 1999);	//send body cr.cr to end
  snprintf (bigbuf, sizeof (bigbuf),
	    "From: %s\nTo: %s\nSubject: %s\nX-Mailer: RTG Mail engine (beta)\nContent-Type: TEXT/PLAIN; charset=US-ASCII\n\n%s\n.\n",
	    odkogo, dokogo, temat, tresc);
  sm_writeln (sockfd, bigbuf);
  k = read (sockfd, bigbuf, 1999);	//queued
  snprintf (bigbuf, sizeof (bigbuf), "quit\n");
  sm_writeln (sockfd, bigbuf);
  k = read (sockfd, bigbuf, 1999);	//bye

  shutdown (sockfd, SHUT_RDWR);
  close (sockfd);
  return 1;
}
