#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <strings.h>

int main(int argc, char *argv[])
{
  int s[2];
  char **args1, **args2;
  int firstarg, lastarg;
  int i;

  if (socketpair(PF_UNIX, SOCK_STREAM, 0, s) < 0)
    {
      fprintf(stderr,"socketpair failed: %s\n",strerror(errno));
      exit(1);
    }

  /* Make this configurable later, but for now it's fine. */

  /* Find the first program to execute. */
  firstarg = 1;
  for(i=1;i<argc;i++)
    {
      if (strcmp(argv[i],"-makesock_connect_to")==0)
	{
	  break;
	}
    }
  lastarg = i;
  if ( (args1=malloc((lastarg-firstarg+1) * sizeof(char *))) == NULL)
    {
      fprintf(stderr,"malloc error: %s\n",strerror(errno));
      exit(1);
    }
  for (i=0;i<(lastarg-firstarg);i++)
    {
      args1[i]=argv[firstarg+i];
    }
  args1[i] = NULL;
  
  lastarg++;

  /* Now find the last program to execute. */
  if ( (args2=malloc((argc-lastarg+1) * sizeof(char *))) == NULL)
    {
      fprintf(stderr,"malloc error: %s\n",strerror(errno));
      exit(1);
    }
  for(i=0;i<(argc-lastarg);i++)
    {
      args2[i] = argv[lastarg+i];
    }
  args2[i] = NULL;

  switch(fork())
    {
    case -1:
      /* Error. */
      exit(1);
    case 0:
      /* Child */
      close(s[0]);
      close(0);
      close(1);
      if (dup2(s[1],0) < 0)
	{
	  fprintf(stderr,"dup2 error: %s\n",strerror(errno));
	  exit(1);
	}
      if (dup2(s[1],1) < 0)
	{
	  fprintf(stderr,"dup2 error: %s\n",strerror(errno));
	  exit(1);
	}
      if (execvp(args2[0],args2) < 0)
	{
	  fprintf(stderr,"execvp error: %s\n",strerror(errno));
	  exit(1);
	}
      break;
    default:
      /* Parent */
      if (s[0] != 3)
	{
	  close(3);
	  if (dup2(s[0],3) < 0)
	    {
	      fprintf(stderr,"dup2 error: %s\n",strerror(errno));
	      exit(1);
	    }
	  if (fcntl(3,F_SETFD,0) == -1) /* Turn off close-on-exec */
	    {
	      fprintf(stderr,"fcntl error: %s\n",strerror(errno));
	      exit(1);
	    }
	}
      if (s[1] != 3)
	close(s[1]);
      if (execvp(args1[0],args1) < 0)
	{
	  fprintf(stderr,"execvp error: %s\n",strerror(errno));
	  exit(1);
	}
      break;
    }
}
  

  
