/*=========================================================================

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/VolViewCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkKWRemoteIOUtilities.h"

// Includes needed for implementation of RenameFile.  This is not in
// system tools because it is not implemented robustly enough to move
// files across directories.
#ifdef _WIN32
# include <windows.h>
# include <sys/stat.h>
#endif

#include "vtkObjectFactory.h"
#include <libtar/libtar.h>
#include <libtar/config.h>

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
//#include <libtar/compat.h>
#include <io.h>
#else
#include <sys/param.h>
#endif

#ifdef STDC_HEADERS
# include <string.h>
#endif

#ifdef HAVE_UNISTD_H
# include <unistd.h>
# include <stdlib.h>
#endif

#ifdef DEBUG
# include <signal.h>
#endif

# include <vtkzlib/zlib.h>
# define cm_zlib_gzdopen gzdopen
# define cm_zlib_gzclose gzclose
# define cm_zlib_gzread gzread
# define cm_zlib_gzwrite gzwrite
#include <sstream>

#include <memory> // for auto_ptr

char *progname;
int mdttar_verbose = 0;
int use_gnu = 0;

#include "vtksys/SystemTools.hxx"

//----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkKWRemoteIOUtilities, "$Revision: 1.8 $");
vtkStandardNewMacro(vtkKWRemoteIOUtilities);

//----------------------------------------------------------------------------
vtkKWRemoteIOUtilities::vtkKWRemoteIOUtilities()
{
}

//----------------------------------------------------------------------------
vtkKWRemoteIOUtilities::~vtkKWRemoteIOUtilities()
{
}

//----------------------------------------------------------------------------
void vtkKWRemoteIOUtilities::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}


struct vtkKWRemoteIOUtilitiesGZStruct
{
  gzFile GZFile;
};

extern "C" {
  int vtkKWRemoteIOUtilitiesGZStructOpen(void* call_data, const char *pathname, 
                                int oflags, mode_t mode);
  int vtkKWRemoteIOUtilitiesGZStructClose(void* call_data);
  ssize_t vtkKWRemoteIOUtilitiesGZStructRead(void* call_data, void* buf, size_t count);
  ssize_t vtkKWRemoteIOUtilitiesGZStructWrite(void* call_data, const void* buf, 
                                     size_t count);
}

int vtkKWRemoteIOUtilitiesGZStructOpen(void* call_data, const char *pathname, 
                              int oflags, mode_t mode)
{
  const char *gzoflags;
  int fd;

  vtkKWRemoteIOUtilitiesGZStruct* gzf = static_cast<vtkKWRemoteIOUtilitiesGZStruct*>(call_data);

  switch (oflags & O_ACCMODE)
  {
  case O_WRONLY:
    gzoflags = "wb";
    break;
  case O_RDONLY:
    gzoflags = "rb";
    break;
  default:
  case O_RDWR:
    errno = EINVAL;
    return -1;
  }

  fd = open(pathname, oflags, mode);
  if (fd == -1)
    {
    return -1;
    }

// no fchmod on BeOS 5...do pathname instead.
#if defined(__BEOS__) && !defined(__ZETA__) 
  if ((oflags & O_CREAT) && chmod(pathname, mode))
    {
    return -1;
    }
#elif !defined(_WIN32) || defined(__CYGWIN__)
  if ((oflags & O_CREAT) && fchmod(fd, mode))
    {
    return -1;
    }
#endif

  gzf->GZFile = gzdopen(fd, gzoflags);
  if (!gzf->GZFile)
  {
    errno = ENOMEM;
    return -1;
  }

  return fd;
}

int vtkKWRemoteIOUtilitiesGZStructClose(void* call_data)
{
  vtkKWRemoteIOUtilitiesGZStruct* gzf = static_cast<vtkKWRemoteIOUtilitiesGZStruct*>(call_data);
  return gzclose(gzf->GZFile);
}

ssize_t vtkKWRemoteIOUtilitiesGZStructRead(void* call_data, void* buf, size_t count)
{
  vtkKWRemoteIOUtilitiesGZStruct* gzf = static_cast<vtkKWRemoteIOUtilitiesGZStruct*>(call_data);
  return gzread(gzf->GZFile, buf, static_cast<int>(count));
}

ssize_t vtkKWRemoteIOUtilitiesGZStructWrite(void* call_data, const void* buf,
                                   size_t count)
{
  vtkKWRemoteIOUtilitiesGZStruct* gzf = static_cast<vtkKWRemoteIOUtilitiesGZStruct*>(call_data);
  return gzwrite(gzf->GZFile, (void*)buf, static_cast<int>(count));
}
  
//----------------------------------------------------------------------------
int vtkKWRemoteIOUtilities::CreateTar(const char* outFileName, 
                              const std::vector<vtkstd::string> & files,
                              const char* rootDirectory,
                              bool gzip, bool verbose)
{
  TAR *t;
  char buf[TAR_MAXPATHLEN];
  char pathname[TAR_MAXPATHLEN];
  vtkKWRemoteIOUtilitiesGZStruct gzs;

  tartype_t gztype = {
    (openfunc_t)vtkKWRemoteIOUtilitiesGZStructOpen,
    (closefunc_t)vtkKWRemoteIOUtilitiesGZStructClose,
    (readfunc_t)vtkKWRemoteIOUtilitiesGZStructRead,
    (writefunc_t)vtkKWRemoteIOUtilitiesGZStructWrite,
    &gzs
  };

  // Ok, this libtar is not const safe. for now use auto_ptr hack
  char* realName = new char[ strlen(outFileName) + 1 ];
  std::auto_ptr<char> realNamePtr(realName);
  strcpy(realName, outFileName);
  int options = 0;
  if(verbose)
    {
    options |= TAR_VERBOSE;
    }
#ifdef __CYGWIN__
  options |= TAR_GNU;
#endif 
  if (tar_open(&t, realName,
      (gzip? &gztype : NULL),
      O_WRONLY | O_CREAT, 0644,
      options) == -1)
    {
    vtkGenericWarningMacro("Problem with tar_open(): ");
    return 0;
    }

  std::vector<vtkstd::string>::const_iterator it;
  for (it = files.begin(); it != files.end(); ++ it )
    {
    strncpy(pathname, it->c_str(), sizeof(pathname));
    pathname[sizeof(pathname)-1] = 0;
    if (pathname[0] != '/' && rootDirectory != NULL)
      {
      snprintf(buf, sizeof(buf), "%s/%s", rootDirectory, pathname);
      }
    else
      {
      strncpy(buf, pathname, sizeof(buf));
      }
    buf[sizeof(buf)-1] = 0;
    if (tar_append_tree(t, buf, pathname) != 0)
      {
      std::ostringstream ostr;
      ostr << "Problem with tar_append_tree(\"" << buf << "\", \"" 
           << pathname << "\"): " << std::ends;
      vtkGenericWarningMacro( << ostr.str().c_str());
      tar_close(t);
      return 0;
      }
    }

  if (tar_append_eof(t) != 0)
    {
    vtkGenericWarningMacro("Problem with tar_append_eof(): ");
    tar_close(t);
    return 0;
    }

  if (tar_close(t) != 0)
    {
    vtkGenericWarningMacro("Problem with tar_close(): ");
    return 0;
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkKWRemoteIOUtilities::
ExtractTar( const char *outFileName, 
            const char *root_name, 
            bool gzip)
{

  TAR *t;

  vtkKWRemoteIOUtilitiesGZStruct gzs;

  tartype_t gztype = {
    vtkKWRemoteIOUtilitiesGZStructOpen,
    vtkKWRemoteIOUtilitiesGZStructClose,
    vtkKWRemoteIOUtilitiesGZStructRead,
    vtkKWRemoteIOUtilitiesGZStructWrite,
    &gzs
  };
  
  // Ok, this libtar is not const safe. for now use auto_ptr hack
  char* realName = new char[ strlen(outFileName) + 1 ];
  std::auto_ptr<char> realNamePtr(realName);
  strcpy(realName, outFileName);

#if 0
  cout << "About to open: " << realName << ", gzip: " << gzip << endl;
  if (!vtksys::SystemTools::FileExists(realName))
    {
    cout << "File does not exist: " << realName << endl;
    }
  cout << "File length: " << vtksys::SystemTools::FileLength(realName) << endl;
#endif
     
  if (tar_open(&t, realName,
      (gzip ? &gztype : NULL),
      O_RDONLY
#ifdef _WIN32
      | O_BINARY
#endif
      , 0, 0))
    {
    vtkGenericWarningMacro("Problem with tar_open(): ");
    return 0;
    }

  bool extracted = false;
  if (root_name)
    {
    char* realRootName = new char[ strlen(root_name) + 1 ];
    std::auto_ptr<char> realRootNamePtr(realRootName);
    strcpy(realRootName, root_name);
    extracted = (tar_extract_all(t, realRootName ) == 0);
    }
  else
    {
    extracted = (tar_extract_all(t, NULL ) == 0);
    }

  if (!extracted)
    {
    vtkGenericWarningMacro("Problem with tar_extract_all(): ");
    return 0;
    }

  if (tar_close(t) != 0)
    {
    vtkGenericWarningMacro( << "Problem with tar_close(): " );
    return 0;
    }
  return 1;
}


//----------------------------------------------------------------------------
int vtkKWRemoteIOUtilities::RenameFile(const char* oldname,
                                       const char* newname)
{
#ifdef _WIN32
  /* On Windows the move functions will not replace existing files.
     Check if the destination exists.  */
  struct stat newFile;
  if(stat(newname, &newFile) == 0)
    {
    /* The destination exists.  We have to replace it carefully.  The
       MoveFileEx function does what we need but is not available on
       Win9x.  */
    OSVERSIONINFO osv;
    DWORD attrs;

    /* Make sure the destination is not read only.  */
    attrs = GetFileAttributes(newname);
    if(attrs & FILE_ATTRIBUTE_READONLY)
      {
      SetFileAttributes(newname, attrs & ~FILE_ATTRIBUTE_READONLY);
      }

    /* Check the windows version number.  */
    osv.dwOSVersionInfoSize = sizeof(osv);
    GetVersionEx(&osv);
    if(osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
      {
      /* This is Win9x.  There is no MoveFileEx implementation.  We
         cannot quite rename the file atomically.  Just delete the
         destination and then move the file.  */
      DeleteFile(newname);
      return MoveFile(oldname, newname);
      }
    else
      {
      /* This is not Win9x.  Use the MoveFileEx implementation.  */
      return MoveFileEx(oldname, newname, MOVEFILE_REPLACE_EXISTING);
      }
    }
  else
    {
    /* The destination does not exist.  Just move the file.  */
    return MoveFile(oldname, newname);
    }
#else
  /* On UNIX we have an OS-provided call to do this atomically.  */
  return rename(oldname, newname) == 0;
#endif
}

