/* winstall -- Installation of GNU Compilation Chain on Windows
   Copyright (C) 2000, 2001 Free Software Foundation, Inc.
   Written by Stephane Carrez (stcarrez@worldnet.fr)	

This file 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, or (at your option) any
later version.

In addition to the permissions in the GNU General Public License, the
Free Software Foundation gives you unlimited permission to link the
compiled version of this file with other programs, and to distribute
those programs without any restriction coming from the use of this
file.  (The General Public License restrictions do apply in other
respects; for example, they cover modification of the file, and
distribution when not linked into another program.)

This file 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; see the file COPYING.  If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.

*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef _WIN32
# include <windows.h>
#endif

#ifndef O_BINARY
# define O_BINARY 0
#endif

#ifdef _WIN32
# define DIR_SEP "\\"
#else
# define DIR_SEP "/"
#endif


static char *prog = "winstall";
static int verbose = 1;
static char cur_dir[PATH_MAX];

/* Print an error message.  */
void
error (const char *msg, ...)
{
  va_list argp;
  int oerrno;

  oerrno = errno;
  va_start (argp, msg);
  fprintf (stderr, "%s: ", prog);
  vfprintf (stderr, msg, argp);
  fprintf (stderr, "\n");
  va_end (argp);

  if (oerrno != 0)
    fprintf (stderr, "%s: %s\n", prog, strerror (oerrno));
  errno = 0;
}

/* Print a message.  */
void
message (const char *msg, ...)
{
  va_list argp;
  int oerrno;
  
  if (verbose == 0)
    return;

  oerrno = errno;
  va_start (argp, msg);
  vfprintf (stdout, msg, argp);
  va_end (argp);
  fflush (stdout);
  errno = oerrno;
}

static const char *programs[] = {
  "addr2line",
  "as",
  "c++filt",
  "gasp",
  "gdb",
  "nm",
  "objdump",
  "readelf",
  "size",
  "strip",
  "ar",
  "c++",
  "cpp",
  "gcc",
  "ld",
  "objcopy",
  "ranlib",
  "run",
  "strings",
  0
};

/* List of executables that must be patched to put the installation
   directory in them.  When building Gcc, and the Binutils, the
   installation directory is configured with a -Dname option.  */
static const char *programs_to_patch[] = {
  "gcc",
  "c++",
  "cpp",
  "ld",
  0
};

static const char *spec_dirs[] = {
  "m6811-elf",
  "m6812-elf",
  0
};

/* Return 1 if the path 'dir' corresponds to a valid directory.  */
static int
isDirectory (const char *dir)
{
  struct stat st;
  int result;

  result = stat (dir, &st);
  return (result == 0 && S_ISDIR (st.st_mode));
}

/* Return 1 if the path 'dir' corresponds to a valid file.  */
static int
isRegularFile (const char *dir)
{
  struct stat st;
  int result;

  result = stat (dir, &st);

  /* Only check for non-directory.  */
  return (result == 0 && !S_ISDIR (st.st_mode));
}

/* Brute force load file.  Allocate a buffer large enought to hold
   the complete file, read that file in one blow and return the buffer.  */
char *
loadFile (const char *file, size_t *size)
{
  int fd;
  char *buffer;
  int bufsize;
  struct stat st;
  int result;

  /* Open the file in binary mode.  */
  fd = open (file, O_BINARY | O_RDONLY);
  if (fd < 0)
    {
      error ("Cannot open file '%s'.", file);
      return 0;
    }

  /* Get its size.  */
  result = fstat (fd, &st);
  if (result < 0)
    {
      error ("Cannot get size of file '%s'.", file);
      close (fd);
      return 0;
    }
  bufsize = st.st_size;
  buffer = (char*) malloc (bufsize);
  if (buffer == 0)
    {
      error ("Not enough memory to allocate %d byte%s.",
             bufsize, bufsize > 1 ? "s" : "");
      close (fd);
      return 0;
    }

  /* Read it in one blow.  */
  result = read (fd, buffer, bufsize);
  if (result < 0)
    {
      error ("Read error when loading '%s'.", file);
      close (fd);
      free (buffer);
      return 0;
    }
  close (fd);
  *size = result;
  
  return buffer;
}

int
copyFile (const char *new_file, const char *cur_file, int mode)
{
  char *buffer;
  int fd;
  size_t len;
  int result;

  buffer = loadFile (cur_file, &len);
  if (buffer == 0)
    return -1;

  fd = open (new_file, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, mode);
  if (fd < 0)
    {
      error ("Cannot create file '%s'.", new_file);
      free (buffer);
      return -1;
    }
  result = write (fd, buffer, len);
  if (result != len)
    {
      error ("Cannot copy file '%s'.", new_file);
      free (buffer);
      close (fd);
      return -1;
    }
  free (buffer);
  close (fd);
  return 0;
}

#define MAGIC_0  (0) /* Must be 0 */
#define MAGIC_1  ('H' | 0)
#define MAGIC_2  ('T' | 0x80)
#define MAGIC_3  ('A' | 0)
#define MAGIC_4  ('P' | 0x80)
#define MAGIC_5  (0) /* Must be length of string (high part)*/
#define MAGIC_6  (0) /* Must be length of string (low part) */
#define MAGIC_7  (0) /* Must be length of install path */
#define MAGIC_8  (0) /* Must be length of install path */

int
patchPathHardWay (const char *file, const char *new_path)
{
  unsigned char *buffer;
  unsigned char *prev_patch_pos;
  size_t file_len;
  size_t new_len;
  size_t len;
  unsigned char *p;
  int patch_done = 0;
  char work_path[1024];
  int fd;
  int result;
  
  static const char *magic_path =
    "/gcc-is-not-yet-installed-please-install-it-using-the-winstall-tool/usr";

  new_len = strlen (new_path);
  if (new_len > strlen (magic_path) - 8)
    {
      error ("Installation directory '%s' has a too long path.", new_path);
      return -1;
    }
  
  /* Load the file in memory (files to patch are reasonably small).  */
  buffer = loadFile (file, &file_len);
  if (buffer == 0)
    return -1;

  prev_patch_pos = buffer;
  for (p = buffer; p < &buffer[file_len];)
    {
      unsigned char *patch_pos;
      unsigned char *patch_end;
      size_t path_len;
      
      patch_pos = 0;

      /* Find a path to replace.  */
      for (; p < &buffer[file_len - 80]; p++)
        {
          /* Search for the original path.  */
          if (strncmp (p, magic_path, strlen (magic_path)) == 0)
            {
              path_len = strlen (magic_path);
              patch_pos = p;
              break;
            }

          /* Search for the magic tags inserted after an installation.
             The tags appear at end of the string containing the path.  */
          if (p[0] == MAGIC_0 && p[1] == MAGIC_1 && p[2] == MAGIC_2
              && p[3] == MAGIC_3 && p[4] == MAGIC_4)
            {
              size_t str_len;

              str_len = ((p[5] & 0x0ff) << 8) | (p[6] & 0x0ff);
              path_len = ((p[7] & 0x0ff) << 8) | (p[8] & 0x0ff);

              /* Invalidate the magic tags.  */
              memset (p, 0, 8);
              patch_pos = &p[- str_len];
              break;
            }
        }

      if (patch_pos == 0)
        break;

      /* Verify that we progress in the patching.  */
      if (patch_pos < prev_patch_pos && patch_pos < &buffer[file_len - 80])
        {
          errno = 0;
          error ("File is corrupted.");
          free (buffer);
          return -1;
        }
      prev_patch_pos = patch_pos;
      
      patch_end = &patch_pos[path_len];
      if (strlen (patch_end) > sizeof (work_path) - strlen (magic_path))
        {
          break;
        }

      /* Build the new path.  */
      strcpy (work_path, new_path);
      if (patch_end[0] != DIR_SEP[0] && work_path[new_len-1] != DIR_SEP[0]
          && patch_end[0] != 0)
        strcat (work_path, DIR_SEP);
      strcat (work_path, patch_end);

      /* Patch the file.  */
      strcpy (patch_pos, work_path);

      /* Put a magic identification so that we can patch again.  */
      patch_pos += strlen (work_path);
      patch_pos[0] = MAGIC_0;
      patch_pos[1] = MAGIC_1;
      patch_pos[2] = MAGIC_2;
      patch_pos[3] = MAGIC_3;
      patch_pos[4] = MAGIC_4;

      /* Dump the length of the string and the length of the installation
         path after the magics so that patching is possible again.  */
      len = strlen (work_path);
      patch_pos[5] = len >> 8;
      patch_pos[6] = len;
      patch_pos[7] = new_len >> 8;
      patch_pos[8] = new_len;

      p = &patch_pos[9];
      patch_done++;
    }

  if (patch_done == 0)
    {
      errno = 0;
      error ("No configuration data found.");
      free (buffer);
      return -1;
    }

  chmod (file, 0755); 
  fd = open (file, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, 0755);
  if (fd < 0)
    {
      error ("Cannot create file '%s'.", file);
      free (buffer);
      return -1;
    }
  result = write (fd, buffer, file_len);
  if (result != file_len)
    {
      error ("Cannot copy file '%s'.", file);
      free (buffer);
      close (fd);
      return -1;
    }
  free (buffer);
  close (fd);
  return 0;
}

static const char *other_patch_files[] = {
  "lib/gcc-lib/m6811-elf/2.95.2/cpp",
  "lib/gcc-lib/m6811-elf/2.95.2/cpp.exe",
  "lib/gcc-lib/m6812-elf/2.95.2/cpp",
  "lib/gcc-lib/m6812-elf/2.95.2/cpp.exe",
  "lib/gcc-lib/m6811-elf/2.95.3/cpp0",
  "lib/gcc-lib/m6811-elf/2.95.3/cpp0.exe",
  "lib/gcc-lib/m6812-elf/2.95.3/cpp0",
  "lib/gcc-lib/m6812-elf/2.95.3/cpp0.exe",
  "lib/gcc-lib/m6811-elf/2.95.3/cc1",
  "lib/gcc-lib/m6811-elf/2.95.3/cc1.exe",
  "lib/gcc-lib/m6812-elf/2.95.3/cc1",
  "lib/gcc-lib/m6812-elf/2.95.3/cc1.exe",
  "lib/gcc-lib/m6811-elf/2.95.3/cc1plus",
  "lib/gcc-lib/m6811-elf/2.95.3/cc1plus.exe",
  "lib/gcc-lib/m6812-elf/2.95.3/cc1plus",
  "lib/gcc-lib/m6812-elf/2.95.3/cc1plus.exe",
  "lib/gcc-lib/m6811-elf/2.95.3/collect2",
  "lib/gcc-lib/m6811-elf/2.95.3/collect2.exe",
  "lib/gcc-lib/m6812-elf/2.95.3/collect2",
  "lib/gcc-lib/m6812-elf/2.95.3/collect2.exe",
  0
};

int
installFiles (const char *dir)
{
  int result;
  char *bin_dir;
  char *spec_dir;
  char *sfile;
  char *dfile;
  int i, j, k;
  int error_count = 0;
  
  message ("Checking installation directory...");
  if (isDirectory (dir) == 0)
    {
      message ("Oops\n");
      error ("The path '%s' is not a valid installation directory.", dir);
      return -1;
    }
  
  bin_dir = (char*) alloca (strlen (dir) + 10);
  sprintf (bin_dir, "%s%sbin", dir, DIR_SEP);
  if (isDirectory (bin_dir) == 0)
    {
      message ("Oops\n");
      error ("The path '%s' is not a valid installation directory.", dir);
      return -1;
    }
  message ("Ok\n");

  spec_dir = (char*) alloca (strlen (dir) + 10);
  sfile = (char*) alloca (strlen (dir) + 256);
  dfile = (char*) alloca (strlen (dir) + 256);
  for (i = 0; spec_dirs[i]; i++)
    {
      sprintf (spec_dir, "%s%s%s%sbin", dir, DIR_SEP, spec_dirs[i], DIR_SEP);
      for (j = 0; programs[j]; j++)
        {
          int add_exe = 0;
          
          sprintf (sfile, "%s%sbin%s%s-%s", dir, DIR_SEP, DIR_SEP,
                   spec_dirs[i], programs[j]);
          if (!isRegularFile (sfile))
            {
              strcat (sfile, ".exe");
              if (!isRegularFile (sfile))
                continue;
              add_exe = 1;
            }

          /* Create the m6811-elf/bin directory if it does not exist.
             This happens when the zip tool does not create directories
             which contain no file.  */
          if (isDirectory (spec_dir) == 0)
            {
              result = mkdir (spec_dir);
              if (result != 0)
                {
                  message ("Oops\n");
                  error ("Cannot create directory '%s'.", spec_dir);
                  return -1;
                }
            }
          sprintf (dfile, "%s%s%s", spec_dir, DIR_SEP, programs[j]);
          if (add_exe)
            strcat (dfile, ".exe");

          message ("Installing '%s'...", dfile);
          result = copyFile (dfile, sfile, 0755);
          if (result < 0)
            {
              message ("Oops\n");
              error_count++;
            }
          else
            {
              message ("Ok\n");
            }

          /* See if the program must be patched.  */
          for (k = 0; programs_to_patch[k]; k++)
            {
              if (strcmp (programs_to_patch[k], programs[j]) == 0)
                {
                  /* Patch the source (in /usr/bin).  */
                  message ("Configuring '%s'...", sfile);
                  result = patchPathHardWay (sfile, dir);
                  if (result < 0)
                    {
                      message ("Oops\n");
                      error_count++;
                    }
                  else
                    {
                      message ("Ok\n");
                    }

                  /* Patch the destination (in /usr/m6811-elf/bin).  */
                  message ("Configuring '%s'...", dfile);
                  result = patchPathHardWay (dfile, dir);
                  if (result < 0)
                    {
                      message ("Oops\n");
                      error_count++;
                    }
                  else
                    {
                      message ("Ok\n");
                    }
                  break;
                }
            }
        }
    }

  for (i = 0; other_patch_files[i]; i++)
    {
      sprintf (sfile, "%s%s%s", dir, DIR_SEP, other_patch_files[i]);
      if (!isRegularFile (sfile))
	continue;

      /* Patch the source (in /usr/bin).  */
      message ("Configuring '%s'...", sfile);
      result = patchPathHardWay (sfile, dir);
      if (result < 0)
	{
	  message ("Oops\n");
	  error_count++;
	}
      else
	{
	  message ("Ok\n");
	}      
    }
  return error_count;
}

char *
getProgramPath (char *arg0)
{
  char path[PATH_MAX];
  size_t len;
  
#ifdef _WIN32
  char drive[_MAX_DRIVE];
  char dir[PATH_MAX];

  return 0;
#if 0
  GetModuleFileName (NULL, path, _MAX_PATH);
  _splitpath (path, drive, dir, (char*)NULL, (char*)NULL);
  _makepath (path, drive, dir, (char*)NULL, (char*)NULL);
#endif
#else
  char *p;
  
  strcpy (path, arg0);
  p = strrchr (path, '/');
  if (p)
    *p = 0;
  else
    strcpy (path, ".");
#endif

  len = strlen (path);
  if (path[0] && strcmp (&path[len - 1], DIR_SEP) == 0)
    {
      path[len - 1] = 0;
    }

  return strdup (path);
}

char *
makeInstallDir (char *dir, int skip)
{
  char *p;
  char *q;
  char *s;
  char *r;
  
  p = (char*) alloca (strlen (dir) + strlen (cur_dir) + 256);

  /* Copy an optional drive specification.  */
  q = strchr (dir, ':');
  if (q)
    {
      *q++ = 0;
#if 0
      strcpy (p, dir);
      strcat (p, ":");
#else
      *p = 0;
#endif
      dir = q;
    }
  else
    {
      *p = 0;
    }

  /* Translate the path into an absolute path.  */
  if (dir[0] != DIR_SEP[0])
    {
      strcat (p, cur_dir);
      strcat (p, DIR_SEP);
    }
  strcat (p, dir);

  /* Remove 'skip' path components at end of the path.  */
  while (skip > 0)
    {
      q = strrchr (p, DIR_SEP[0]);
      if (q == 0)
        {
          errno = 0;
          error ("Invalid directory '%s'.", dir);
          return 0;
        }

      *q = 0;
      skip--;
    }

  r = (char*) alloca (strlen (p));
  s = r;
  *r = 0;
  for (q = p; q[0]; )
    {
      char c;
      
      /* Remove a ./ in the path.  */
      if (strncmp (q, "./", 2) == 0 || strncmp (q, ".\\", 2) == 0)
        {
          q += 2;
          continue;
        }

      /* Remove ../ and remove last component of the current directory
         path.  */
      if (strncmp (q, "../", 3) == 0 || strncmp (q, "..\\", 3) == 0)
        {
          char *last = strrchr (s, DIR_SEP[0]);

          if (last == 0)
            {
              errno = 0;
              error ("Invalid directory '%s'.", dir);
              return 0;
            }
          if (last[1] == 0)
            {
              *last = 0;
              last = strrchr (s, DIR_SEP[0]);
              if (last == 0)
                {
                  errno = 0;
                  error ("Invalid directory '%s'.", dir);
                  return 0;
                }
            }
          r = last + 1;
          *r = 0;
          q += 3;
          continue;
        }

      while ((c = *r++ = *q++) && c != DIR_SEP[0])
        continue;

      if (c)
        *r = 0;
    }

  if (r > &s[1] && r[-1] == DIR_SEP[0] && (r < &s[2] || r[-2] != ':'))
    r[-1] = 0;
  return strdup (s);
}

/* Check that 'dir' corresponds to the 'bin' directory of the install
   tree.  */
static int
isBinDirectory (char *dir)
{
  static const char *check_files[] = {
    "m6811-elf-gcc",
    "m6811-elf-gcc.exe",
    "m6812-elf-gcc",
    "m6812-elf-gcc.exe",
    0
  };
  char *p;
  int i;

  if (isDirectory (dir) == 0)
    return 0;
  
  p = alloca (strlen (dir) + 32);
  for (i = 0; check_files[i]; i++)
    {
      sprintf (p, "%s%s%s", dir, DIR_SEP, check_files[i]);
      if (isRegularFile (p))
        return 1;
    }
  return 0;
}

/* Try to find the installation directory using 'dir' as a path.
   Returns the installation directory that was found or NULL.  */
static char *
tryInstallDirectory (char *dir)
{
  char *p;

  if (isBinDirectory (dir))
    return makeInstallDir (dir, 1);

  p = alloca (strlen (dir) + 256);
  sprintf (p, "%s%sm6811%sbin", dir, DIR_SEP, DIR_SEP);
  if (isBinDirectory (p))
    return makeInstallDir (p, 1);
  
  sprintf (p, "%s%susr%sbin", dir, DIR_SEP, DIR_SEP);
  if (isBinDirectory (p))
    return makeInstallDir (p, 1);

  sprintf (p, "%s%sbin", dir, DIR_SEP);
  if (isBinDirectory (p))
    return makeInstallDir (p, 1);

  return 0;
} 
  
char *
getInstallPath (char *arg0)
{
  char *install_prog;
  char *p;

  /* Try with current directory.  */
  p = tryInstallDirectory (cur_dir);
  if (p)
    return p;

  /* Get path of install program.  */
  install_prog = getProgramPath (arg0);
  if (install_prog)
    {
      p = tryInstallDirectory (install_prog);
      if (p)
        return p;
    }
  
  errno = 0;
  error ("Cannot find the installation directory.");
  error ("Please, extract the ZIP files first or pass the installation");
  error ("directory as argument to the installation program.");
  return 0;
}

char *
translate_path (char *p)
{
  char *s;
  char *q;

  s = strdup (p);
  q = s;
  while (*q)
    {
      if (*q == '/')
        *q = DIR_SEP[0];
      q++;
    }
  printf ("New path = |%s| old = |%s|\n", s, p);
  return s;
}

void
usage ()
{
  printf ("Usage: %s [-v|--verbose] [-q|--quiet] [-h|--help] [install-dir]\n",
          prog);
}

void
help ()
{
  printf ("Installation of GNU Development Chain for 68HC11 & 68HC12\n"
          "for a Windows 95, 98 and NT hosts.\n\n");
  usage ();
  printf ("\n");
  printf ("[install-dir] is the optional installation directory path.\n");
  printf ("The installation program normally finds that path automatically\n");
  printf ("but you can override it or change it in case it is not correct.\n");
  printf ("\n");
  printf (" -v, --verbose   Verbose installation mode\n");
  printf (" -q, --quiet     Quiet installation mode\n");
  printf (" -h, --help      Print this help\n");
}
  
int
main (int argc, char *argv[])
{
  char *dir;
  char *p;
  int result;
  char *install_dir;
  int i;

  install_dir = 0;
  
  /* Parse some options.  */
  for (i = 1; i < argc; i++)
    {
      if (strcmp (argv[i], "-v") == 0
          || strcmp (argv[i], "--verbose") == 0)
        {
          verbose = 1;
        }
      else if (strcmp (argv[i], "-q") == 0
               || strcmp (argv[i], "--quiet") == 0)
        {
          verbose = 0;
        }
      else if (strcmp (argv[i], "-h") == 0
               || strcmp (argv[i], "--help") == 0)
        {
          help ();
          exit (2);
        }
      else if (argv[i][0] == '-' || install_dir)
        {
          usage ();
          exit (2);
        }
      else
        {
          install_dir = translate_path (argv[i]);
        }
    }
  message ("Installation of GNU Development Chain for 68HC11 & 68HC12\n");
  
  /* Get current directory.  */
  p = getcwd (cur_dir, sizeof (cur_dir));
  if (p == 0)
    {
      error ("Cannot identify current directory.");
      return 1;
    }

  if (install_dir)
    {
      dir = tryInstallDirectory (install_dir);
      if (dir == 0)
        {
          errno = 0;
          error ("Directory '%s' does not correspond to an installation "
                 "directory.", install_dir);
          return 1;
        }
    }
  else
    {
      dir = getInstallPath (argv[0]);
      if (dir == 0)
        return 1;
    }

  message ("Using '%s' as installation directory\n", dir);
  result = installFiles (dir);
  free (dir);

  if (result == 0)
    message ("Installation is complete.\n");
  else
    message ("Installation failed.\n");
  
  return result == 0 ? 0 : 1;
}
