/* -copyright-
#-# 
#-# Copyright (C) 1999-2001  Robin Hogan, 2021-2026 Willem Vermin
#-# 
#-# This program is free software; you can redistribute it and/or modify
#-# it under the terms of the GNU General Public License as published by
#-# the Free Software Foundation; either version 2 of the License, or
#-# (at your option) any later version.
#-# 
#-# This program is distributed in the hope that it will be useful,
#-# but WITHOUT ANY WARRANTY; without even the implied warranty of
#-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#-# GNU General Public License for more details.
#-# 
#-# You should have received a copy of the GNU General Public License
#-# along with this program; if not, write to the Free Software
#-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#-# 
 */
#include <stdio.h>
#include <unistd.h>
#ifdef SELFREP
#include "selfrep.h"
static unsigned char tarfile[] = {
#include "tarfile.inc"
};
#endif

#ifdef SELFREP
static ssize_t mywrite(int fd, const void *buf, size_t count);
#endif

void selfrep()
{
#ifdef SELFREP
   if(sizeof(tarfile) > 1000 && isatty(fileno(stdout)))
   {
      printf("Not sending tar file to terminal.\n");
      printf("Try redirecting to a file (e.g: xpenguins -selfrep > xpenguins.tar.gz),\n");
      printf("or use a pipe (e.g: xpenguins -selfrep | tar zxf -).\n"); 
   }
   else
   {
      ssize_t rc = mywrite(fileno(stdout),tarfile,sizeof(tarfile));
      if (rc < 0)
	 fprintf(stderr,"Xroach: Problems encountered during production of the tar ball.\n");
   }
#else
   // Since the -selfrep flag is not recognized in this case,
   // the following is somewhat superfluous:
   printf("Self replication is not compiled in.\n");
#endif
}

#ifdef SELFREP
ssize_t mywrite(int fd, const void *buf, size_t count)
{
   const size_t m = 4096; // max per write
   size_t w       = 0;    // # written chars           
   char *b        = (char *)buf;

   while (w < count)
   {
      size_t l = count - w;
      if (l > m)
	 l = m;
      ssize_t x = write(fd, b+w, l);
      if (x < 0)
	 return -1;
      w += x;
   }
   return 0;
}
#endif

