/* 
 * Distributed under the terms of the GNU General Public License v2
 * $Header: $
 *
 * Ramereth made me do it.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define REMOTE_IP	"127.0.0.1"
#define REMOTE_PORT	5667

#define TIMEOUT		10
#define EXIT_DELAY	30
#define BUFLEN		512

#define PORTPIPE_TIMEOUT (getenv("PORTPIPE_TIMEOUT") != NULL ? atoi(getenv("PORTPIPE_TIMEOUT")) : EXIT_DELAY)

void pexit(char *str)
{
   perror(str);
   exit(EXIT_FAILURE);
}

void usage(int argc, char **argv)
{
   printf("Usage: piped data | %s <ip> <port>\n"
	  " - The environment PORTPIPE_TIMEOUT=%d effects the program\n",
	  argv[0], PORTPIPE_TIMEOUT);
   exit(EXIT_FAILURE);
}

int main(int argc, char **argv)
{
   struct sockaddr_in sin_other;
   FILE *fp;
   int i, fd;
   char buf[BUFLEN];

   if ((argc != 3) && (ttyname(0) != NULL))
      usage(argc, argv);
   if (argc > 1)
      if (argv[1][0] == '-')
	 usage(argc, argv);

   if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
      pexit("socket");

   memset((char *) &sin_other, sizeof(sin_other), 0);
   sin_other.sin_family = AF_INET;
   sin_other.sin_port = htons((argc > 2) ? atoi(argv[2]) : REMOTE_PORT);
   if (inet_aton(((argc > 1) ? argv[1] : REMOTE_IP), &sin_other.sin_addr)
       == 0) {
      fprintf(stderr, "inet_aton() failed\n");
      exit(EXIT_FAILURE);
   }

   alarm(TIMEOUT);
   if (connect
       (fd, (struct sockaddr *) &sin_other,
	sizeof(struct sockaddr_in)) < 0)
      pexit("connect");
   alarm(0);

   if ((fp = fdopen(fd, "r+")) == NULL)
      pexit("fdopen");

   while ((fgets(buf, sizeof(buf), stdin)) != NULL) {
      putchar('*');
      fflush(stdout);
      sleep(1);
      fprintf(fp, "%s", buf);
      fflush(fp);
   }
   for (i = 0; i != PORTPIPE_TIMEOUT; i++) {
      putchar('.');
      fflush(stdout);
      sleep(1);
   }
   putchar('\n');
   fclose(fp);
   close(fd);
   exit(EXIT_SUCCESS);
}
