/*
copyright (c) 2008 Kazuki IWAMOTO http://www.maid.org/ iwm@maid.org

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char *
x_strdup (const char *str)
{
  char *p = NULL;

  if (str)
    {
      p = malloc ((strlen (str) + 1) * sizeof (char));
      strcpy (p, str);
    }
  return p;
}


char *
x_strcat (char *str, ...)
{
  char *p;
  size_t len;
  va_list args;

  len = (str ? strlen (str) : 0) + 1;
  va_start (args, str);
  while (p = va_arg (args, char *))
    len += strlen (p);
  va_end (args);
  str = str ? realloc (str, len * sizeof (char)) : calloc (len, sizeof (char));
  va_start (args, str);
  while (p = va_arg (args, char *))
    strcat (str, p);
  va_end (args);
  return str;
}


char **
x_strv_split (const char *str,
              const char *del)
{
  char **strv = NULL;

  if (str && del)
    {
      const char *p;
      size_t i = 0;

      p = str;
      while (*p != '\0')
        {
          char *q;

          strv = realloc (strv, (i + 1) * sizeof (char *));
          q = strstr (p, del);
          if (q)
            {
              size_t len;

              len = q - p;
              strv[i] = malloc ((len + 1) * sizeof (char));
              memcpy (strv[i], p, len);
              (strv[i])[len] = '\0';
              p += len + strlen (del);
            }
          else
            {
              strv[i] = x_strdup (p);
              p += strlen (p);
            }
          i++;
        }
      strv = realloc (strv, (i + 1) * sizeof (char *));
      strv[i] = NULL;
    }
  return strv;
}


size_t
x_strv_length (const char **strv)
{
  size_t length = 0;

  if (strv)
    while (strv[length])
      length++;
  return length;
}


void
x_strv_free (char **strv)
{
  if (strv)
    {
      char **p;

      for (p = strv; *p; p++)
        free (*p);
      free (strv);
    }
}


char *
x_fgets (FILE *fp)
{
  char buf[BUFSIZ], *str = NULL;

  while (fgets (buf, BUFSIZ, fp))
    {
      char c = '\0';
      size_t len;

      len = strlen (buf);
      if (len > 0)
        {
          c = buf[len - 1];
          if (c == '\n')
            buf[--len] = '\0';
        }
      str = x_strcat (str, buf, NULL);
      if (c == '\n')
        break;
    }
  return str;
}


typedef struct _DIFF
{
  char **line;
  int a[4];
  size_t count;
} DIFF;
typedef struct _SOURCE
{
  char *name, *str;
  size_t count;
  DIFF *diff;
} SOURCE;


static int
compare (const void *arg1,
         const void *arg2)
{
  return ((DIFF *)arg1)->a[0] - ((DIFF *)arg2)->a[0];
}


int
main (int   argc,
      char *argv[])
{
  char *str, *file = NULL;
  int i, strip = -1;
  size_t count = 0;
  FILE *fp;
  SOURCE *src = NULL;

  /* 引数 */
  for (i = 1; i < argc; i++)
    if (strcmp (argv[i], "-i") == 0)
      file = argv[++i];
    else if (strncmp (argv[i], "--input=", 8) == 0)
      file = argv[i] + 8;
    else if (strncmp (argv[i], "-p", 2) == 0)
      strip = atoi (argv[i] + 2);
    else if (strncmp (argv[i], "--strip=", 8) == 0)
      strip = atoi (argv[i] + 8);
    else if (strcmp (argv[i], "-f") != 0 && strcmp (argv[i], "--force") != 0
        && strcmp (argv[i], "-s") != 0 && strcmp (argv[i], "--silent") != 0
        && strcmp (argv[i], "-t") != 0 && strcmp (argv[i], "--batch") != 0
        && strcmp (argv[i], "-u") != 0 && strcmp (argv[i], "--unified") != 0
                                        && strcmp (argv[i], "--quiet") != 0)
      return -1;
  if (file && strcmp (file, "-") == 0)
    file = NULL;
  /* パッチ読み込み */
  if (file)
    {
      fp = fopen (file, "r");
      if (!fp)
        return -1;
    }
  else
    {
      fp = stdin;
    }
  /* パッチ解析 */
  while (str = x_fgets (fp))
    {
      if (str[0] == '+' && str[1] == '+' && str[2] == '+')
        {
          char *p, *q;
          size_t len;

          src = realloc (src, (count + 1) * sizeof (SOURCE));
          src[count].str = NULL;
          src[count].count = 0;
          src[count].diff = NULL;
          /* パス抽出 */
          for (p = str + 3; isspace (*p); p++);
          for (q = p; isgraph (*q); q++);
          *q = '\0';
          src[count].name = x_strdup (p);
          count++;
        }
      else if (str[0] == '@' && str[1] == '@')
        {
          char c[5], *p, *q;
          int j;
          size_t len;
          SOURCE *s;
          DIFF *d;

          if (count <= 0)
            return -1;
          s = src + count - 1;
          s->diff = realloc (s->diff, (s->count + 1) * sizeof (DIFF));
          d = s->diff + s->count;
          d->line = NULL;
          d->count = 0;
          /* パッチ行 */
          for (p = str + 2, q = str; *p != '\0'; p++)
            if (isgraph (*p))
              *q++ = *p;
          *q = '\0';
          len = strlen (str);
          if (len < 6 || str[len - 2] != '@' || str[len - 1] != '@')
            return -1;
          str[len - 2] = str[len - 1] = '\0';
          /* 記号 */
          for (i = 0, p = str; *p != '\0'; p++)
            if (!isdigit (*p))
              {
                if (i >= 4)
                  return -1;
                c[i++] = *p;
              }
          c[i] = '\0';
          /* 数値 */
          for (i = j = 0, p = str + 1; i < 4; i++)
            {
              if (i == 0 || i == 2 || c[j] == ',')
                {
                  for (q = p; isdigit (*q); q++);
                  *q = '\0';
                  d->a[i] = atoi (p);
                  p = q + 1;
                  j++;
                }
              else if (i == 1 || i == 3)
                {
                  d->a[i] = 1;
                }
              else
                {
                  return -1;
                }
            }
          for (i = 0; i < 4; i++)
            if (d->a[i] <= 0)
              return -1;
          /* 修正部分 */
          free (str);
          i = j = 0;
          while (i < d->a[1] || j < d->a[3])
            {
              if (!(str = x_fgets (fp))
                        || (str[0] != ' ' && str[0] != '+' && str[0] != '-'))
                return -1;
              if (str[0] == ' ' || str[0] == '-')
                i++;
              if (str[0] == ' ' || str[0] == '+')
                j++;
              d->line = realloc (d->line, (d->count + 1) * sizeof (char *));
              d->line[d->count++] = str;
            }
          if (i != d->a[1] || j != d->a[3])
            return -1;
          str = NULL;
          s->count++;
        }
      free (str);
    }
  if (file && fclose (fp) != 0)
    return -1;
  /* パス加工 */
  for (i = 0; i < count; i++)
    {
      char *p;
      int j, k = 0;
      SOURCE *s;

      s = src + i;
      for (j = 0; s->name[j] != '\0'; j++)
        if (s->name[j] != '/' || s->name[j + 1] != '/')
          s->name[k++] = s->name[j];
      s->name[k] = '\0';
      if (strip < 0)
        {
          p = strrchr (s->name, '/');
          if (p)
            p++;
          else
            p = s->name;
        }
      else
        {
          p = s->name;
          for (j = 0; j < strip; j++)
            {
              p = strchr (p, '/');
              if (!p)
                return -1;
              p++;
            }
        }
      memmove (s->name, p, (strlen (p) + 1) * sizeof (char));
      for (j = 0; s->name[j] != '\0'; j++)
        if (s->name[j] == '/')
          s->name[j] = '\\';
      qsort (s->diff, s->count, sizeof (DIFF), compare);
    }
  /* ファイル変更 */
  for (i = 0; i < count; i++)
    {
      char *crlf, **strv;
      int j, line = 0;
      long fs;
      size_t len;
      SOURCE *s;

      s = src + i;
      if (!(fp = fopen (s->name, "rb"))
            || fseek (fp, 0, SEEK_END) != 0 || (fs = ftell (fp)) < 0
            || !(str = malloc (fs)) || fseek (fp, 0, SEEK_SET) != 0
            || fread (str, sizeof (char), fs, fp) != fs || fclose (fp) != 0)
        return -1;
      if (strstr (str, "\n\r"))
        crlf = "\n\r";
      else if (strchr (str, '\r'))
        crlf = "\r";
      else
        crlf = "\n";
      strv = x_strv_split (str, crlf);
      free (str);
      len = x_strv_length (strv);
      for (j = 0; j < s->count; j++)
        {
          int k;
          DIFF *d;

          d = s->diff + j;
          d->a[0]--;
          if (d->a[0] < line || len <= d->a[0] + d->a[1])
            return -1;
          while (line < d->a[0])
            s->str = x_strcat (s->str, strv[line++], crlf, NULL);
          for (k = 0; k < d->count; k++)
            {
              if (((d->line[k])[0] == ' ' || (d->line[k])[0] == '-')
                                && strcmp (strv[line++], d->line[k] + 1) != 0)
                return -1;
              if ((d->line[k])[0] == ' ' || (d->line[k])[0] == '+')
                s->str = x_strcat (s->str, d->line[k] + 1, crlf, NULL);
              free (d->line[k]);
            }
          free (d->line);
        }
      free (s->diff);
      while (line < len)
        s->str = x_strcat (s->str, strv[line++], crlf, NULL);
      x_strv_free (strv);
    }
  /* ファイル書き込み */
  for (i = 0; i < count; i++)
    {
      size_t len;
      SOURCE *s;

      s = src + i;
      len = strlen (s->str);
      if (!(fp = fopen (s->name, "wb"))
                            || fwrite (s->str, sizeof (char), len, fp) != len
                            || fclose (fp) != 0)
        return -1;
    }
  return 0;
}
