/*
 *  DJGPP specific helpers for CVS.
 */

#ifndef __DJGPP_H__
# define __DJGPP_H__

# include <stdlib.h>
# include <sys/stat.h>
# include <dirent.h>

# define SYSTEM_INITIALIZE(pargc, pargv)  djgpp_cvs_init(pargc, pargv)

# define HAS_EXE_EXTENSION(n)  ((*--(n) == 'e' || *(n) == 'E') && \
                                (*--(n) == 'x' || *(n) == 'X') && \
                                (*--(n) == 'e' || *(n) == 'E') && \
                                 *--(n) == '.')

static char dos_starting_dir[PATH_MAX] = ".";


/* Restore the starting directory to its original value.  Called at exit.  */
static void
return_to_starting_directory(void)
{
  int orig_errno = errno;

  if (chdir(dos_starting_dir) < 0)
    error(0, errno, "%s", dos_starting_dir);
  errno = orig_errno;
}

static void
djgpp_cvs_init(int* pargc, char*** pargv)
{
  /*
   *  Set program name, switch backslash to slash
   *  and strip the ".exe extension.
   */
  char *full_name = _truename((*pargv)[0], NULL);

  if (full_name)
  {
    char *c = full_name;

    for (; *c; c++)
      if (*c == '\\')
        *c = '/';

    if (HAS_EXE_EXTENSION(c))
      *c = '\0';  /*  Strip .exe extension from file name.  */

    free((*pargv)[0]);
    (*pargv)[0] = full_name;
  }


  /*
   *  This is required so that cvs recognizes the CVS directory.
   */
  __opendir_flags |= __OPENDIR_PRESERVE_CASE;


  /*
   *  On MS-DOS, CWD is global, so we must remember where we were before
   *  changing dirs, and return there if the program is interrupted by SIGINT.
   */
  getcwd(dos_starting_dir, PATH_MAX);
  atexit(return_to_starting_directory);
}

#endif  /* __DJGPP_H__ */
