/* -copyright-
#-# Copyright: 2015-2025 Willem Vermin wvermin@gmail.com
#-# 
#-# License: BSD-3-Clause
#-#  Redistribution and use in source and binary forms, with or without
#-#  modification, are permitted provided that the following conditions
#-#  are met:
#-#  1. Redistributions of source code must retain the above copyright
#-#     notice, this list of conditions and the following disclaimer.
#-#  2. Redistributions in binary form must reproduce the above copyright
#-#     notice, this list of conditions and the following disclaimer in the
#-#     documentation and/or other materials provided with the distribution.
#-#  3. Neither the name of the copyright holder nor the names of its
#-#     contributors may be used to endorse or promote products derived
#-#     from this software without specific prior written permission.
#-#   
#-#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#-#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#-#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#-#  A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE HOLDERS OR
#-#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#-#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#-#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#-#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#-#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#-#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#-#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * */

#include <iostream>
#include <unistd.h>
#include "docs.h"

#ifdef SELFREP
static 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;
}

static unsigned char tarfile[] = {
#include "tarfile.inc"
};
void Docs::selfrep()
{
   if(sizeof(tarfile) > 1000 && isatty(fileno(stdout)))
   {
      std::cout << "Not sending tar file to terminal." << std::endl;
      std::cout << "Try redirecting to a file (e.g: findent -selfrep > findent.tar.gz)," << std::endl;
      std::cout << "or use a pipe (e.g: findent -selfrep | tar zxf -)." << std::endl; 
   }
   else
   {
      // This is for the Windows version, to prevent the output
      // of a carriage return after a newline.
      // Alas, this does not work. Any solution?
      FILE *const out = fdopen(dup(fileno(stdout)),"wb");
      ssize_t rc = mywrite(fileno(out),tarfile,sizeof(tarfile));
      if (rc < 0)
	 std::cerr << "findent: Problems encountered during production of the tar ball." << std::endl;
      fclose(out);
   }
}
#endif
