#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char **argv)
{
  char buf[1];
  int fd[2], ssh, sendm, fetchm;
  pid_t pid;

  pipe(fd);
  if((ssh=fork())>0) {
    close(fd[1]);
    /* sleep(10); */
    if(read(fd[0], buf, 1)>0) {
      if(!(fetchm=fork())) {
        execlp("fetchmail", "fetchmail", "-f", "/etc/fetchmailrc", 0); 
        exit(1);
      }
      if(!(sendm=fork())) {
        execlp("sendmail", "sendmail", "-qf", 0); 
        exit(1);
      }
      while(fetchm || sendm) {
        pid=wait(0);
	if(pid==fetchm) fetchm=0;
	if(pid==sendm) sendm=0;
      }
      kill(ssh, SIGTERM);
      wait(0);
    } else
      printf("SSH tunnel creation failed.\n");
  } else {
    dup2(fd[1], 1); close(fd[0]); close(fd[1]);
    execvp(*(argv+1), argv+1); exit(1);
  }
  return 0;
}

