#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "config.h"
#include "tailor.h"
#include "gzip.h"

/* ============================================================
 * Make a file name valid for file systems supported by DJGPP.
 * This includes replacing characters that aren't allowed in
 * file names, and renaming files whose names are reserved by
 * character device drivers.  Characters that aren't allowed
 * depend on the filesystem where the file resides.
 */
void make_valid_dosw32_name(char *name)
{
  /* The following characters aren't allowed in DOS file names.
     Some of them aren't allowed by Windows 9X; these begin at
     offset 7 (zero-based) in the string below.  */
  static char disallowed_chars[] = "+, ;=[]|<>\\\":?*";
  static char replacement_char[] = "x'_`_{}!()%'-^#";
  int long_names = HAVE_LONG_FILE_NAMES(ofname);
  struct stat st;
  register char *p = name;

  /* If the filesystem disallows multiple dots, remove
     all but the last one.  */
  if (!long_names)
    make_simple_name(name);

  /* If there are any more invalid characters, replace them.  */
  for ( ; *p != '\0'; p++)
  {
    register int i;

    for (i = long_names ? 7 : 0; i < sizeof(disallowed_chars); i++)
      if (*p == disallowed_chars[i])
      {
        *p = replacement_char[i];
        break;
      }
  }

  /* The list of character devices is not constant: it depends on
     what device drivers did they install in their CONFIG.SYS.
     `stat' will tell us if the file name is a character device.  */
  if (stat(name, &st) == 0 && S_ISCHR(st.st_mode))
  {
    /* If it's a reserved name, prepend a '_' to it.  */
    memmove(name + 1, name, strlen(name) + 1);
    name[0] = '_';
  }
}
