/* cmd-apply-delta.c:
 *
 ****************************************************************
 * Copyright (C) 2003 Tom Lord
 *
 * See the file "COPYING" for further information about
 * the copyright and warranty status of this work.
 */




#include "config-options.h"
#include "hackerlab/cmd/main.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/fs/cwd.h"
#include "tla/libfsutils/tmp-files.h"
#include "tla/libfsutils/rmrf.h"
#include "tla/libfsutils/dir-as-cwd.h"
#include "tla/libarch/namespace.h"
#include "tla/libarch/project-tree.h"
#include "tla/libarch/my.h"
#include "tla/libarch/archive.h"
#include "tla/libarch/pristines.h"
#include "tla/libarch/local-cache.h"
#include "tla/libarch/make-changeset.h"
#include "tla/libarch/copy-project-tree.h"
#include "tla/libarch/apply-changeset.h"
#include "tla/libarch/merge-three-way.h"
#include "tla/libarch/cmd.h"
#include "tla/libarch/cmd-get.h"
#include "tla/libarch/cmd-delta.h"
#include "tla/libarch/cmd-apply-delta.h"


/* __STDC__ prototypes for static functions */
static void apply_delta_callback (void * vfd, const char * fmt, va_list ap);



static t_uchar * usage = "[options] FROM(REVISION|DIR) TO(REVISION|DIR)";
static t_uchar * version_string = (cfg__std__package " from regexps.com\n"
                                   "\n"
                                   "Copyright 2003 Tom Lord\n"
                                   "\n"
                                   "This is free software; see the source for copying conditions.\n"
                                   "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n"
                                   "PARTICULAR PURPOSE.\n"
                                   "\n"
                                   "Report bugs to " cfg__tla_bug_mail ".\n"
                                   "\n"
                                   cfg__std__release_id_string
                                   "\n");

#define OPTS(OP) \
  OP (opt_help_msg, "h", "help", 0, \
      "Display a help message and exit.") \
  OP (opt_long_help, "H", 0, 0, \
      "Display a verbose help message and exit.") \
  OP (opt_version, "V", "version", 0, \
      "Display a release identifier string\n" \
      "and exit.") \
  OP (opt_archive, "A", "archive", 1, \
      "Override `my-default-archive'") \
  OP (opt_forward, "N", "forward", 0, \
      "pass the --forward option to `patch'") \
  OP (opt_cache, 0, "cache DIR", 1, \
      "specify a cache root for pristine copies") \
  OP (opt_dir, "d", "dir DIR", 1, \
      "Operate on project tree in DIR (default `.')") \
  OP (opt_three_way, "t", "three-way", 0, \
      "Perform a 3-way (diff3-style) merge.") \
  OP (opt_dest, 0, "dest DEST", 1, \
      "Instead of modifying the project tree in-place,\n" \
      "make a copy of it to DEST and apply the result to that") \
  OP (opt_unescaped, 0, "unescaped", 0, \
      "show filenames in unescaped form")


t_uchar arch_cmd_apply_delta_help[] =
  ("compute a changeset between any two trees or revisions and apply it to a project tree\n"

   "A delta between A and B (both of which may be either a full revision or\n"
   "a project tree) is computed, and then applied to the project tree.\n"
   "\n"
   "Exit Status Codes:\n"
   "\n"
   "    0  No conflict during patch\n"
   "    1  Conflicts occurred during patch\n"
   "    3  Internal Error\n");

enum options
{
  OPTS (OPT_ENUM)
};

static struct opt_desc opts[] =
{
  OPTS (OPT_DESC)
    {-1, 0, 0, 0, 0}
};

static void 
do_three_way(int chatter_fd, t_uchar * cache_dir, t_uchar * default_archive, t_uchar * upon_root, t_uchar * from_spec, t_uchar * to_spec, int escape_classes);



int
arch_cmd_apply_delta (t_uchar * program_name, int argc, char * argv[])
{
  int o;
  struct opt_parsed * option;
  int three_way = 0;
  t_uchar * default_archive = 0;
  t_uchar * cache_dir = 0;
  t_uchar * upon = 0;
  t_uchar * dest = 0;
  int forward = 0;
  int exit_status = 0;
  int escape_classes = arch_escape_classes;

  safe_buffer_fd (1, 0, O_WRONLY, 0);

  option = 0;

  while (1)
    {
      o = opt_standard (lim_use_must_malloc, &option, opts, &argc, argv, program_name, usage, version_string, arch_cmd_apply_delta_help, opt_help_msg, opt_long_help, opt_version);
      if (o == opt_none)
        break;
      switch (o)
        {
        default:
          safe_printfmt (2, "unhandled option `%s'\n", option->opt_string);
          panic ("internal error parsing arguments");

        usage_error:
          opt_usage (2, argv[0], program_name, usage, 1);
          exit (1);

          /* bogus_arg: */
          safe_printfmt (2, "ill-formed argument for `%s' (`%s')\n", option->opt_string, option->arg_string);
          goto usage_error;

        case opt_archive:
          {
            lim_free (0, default_archive);
            default_archive = str_save (0, option->arg_string);
            break;
          }

        case opt_cache:
          {
            lim_free (0, cache_dir);
            cache_dir = str_save (0, option->arg_string);
            break;
          }

        case opt_three_way:
          {
            three_way = 1;
            break;
          }

        case opt_dir:
          {
            lim_free (0, upon);
            upon = str_save (0, option->arg_string);
            break;
          }

        case opt_dest:
          {
            lim_free (0, dest);
            dest = str_save (0, option->arg_string);
            break;
          }

        case opt_forward:
          {
            forward = 1;
            break;
          }

	case opt_unescaped:
	  {
	    escape_classes = 0;
	    break;
	  }
        }
    }

  if (argc != 3)
    goto usage_error;

  if (default_archive && !arch_valid_archive_name (default_archive))
    {
      safe_printfmt (2, "%s: invalid archive name (%s)\n",
                     argv[0], default_archive);
      exit (1);
    }

  default_archive = arch_my_default_archive (default_archive);

  {
    t_uchar * from_spec;
    t_uchar * to_spec;
    t_uchar * changeset = 0;
    t_uchar * upon_root = 0;

    from_spec = argv[1];
    to_spec = argv[2];

    if (! upon)
      upon = str_save (0, ".");

    upon_root = arch_tree_root (0, upon, 0);

    if (dest)
      {
        t_uchar * dest_dir = file_name_directory_file (0, dest);

        if (! dest_dir)
          dest_dir = str_save (0, ".");

        changeset = tmp_file_name (dest_dir, ",,apply-delta-changeset");

        safe_printfmt (1, "* copying %s to %s\n", upon, dest);
        arch_copy_project_tree (upon, dest, 1, 1);

        lim_free (0, dest_dir);
      }
    else
      {
        dest = str_save (0, upon);
        changeset = tmp_file_name (dest, ",,apply-delta-changeset");
      }
    if (three_way)
      {
        do_three_way(1, cache_dir, default_archive, upon_root, from_spec, to_spec, escape_classes);
      }

    else
      {
        if (cache_dir)
          arch_call_cmd (arch_cmd_delta, argv[0],
                         "--cache", cache_dir, "-A", default_archive, from_spec, to_spec, changeset,
                         ((escape_classes == 0) ? "--unescaped" : (char*)0),
                         (char*)0);
        else
          arch_call_cmd (arch_cmd_delta, argv[0],
                         "-A", default_archive, from_spec, to_spec, changeset,
                         ((escape_classes == 0) ? "--unescaped" : (char*)0),
                         (char*)0);

        {
          struct arch_apply_changeset_report r = {0, };

          r.callback = apply_delta_callback;
          r.thunk = (void *)1;

          safe_printfmt (1, "* applying changeset\n");

          arch_apply_changeset (&r, changeset, dest, arch_unspecified_id_tagging, arch_inventory_unrecognized, 0, forward, 0, 0, 0, escape_classes);

          exit_status = arch_conflicts_occured (&r);

          arch_free_apply_changeset_report_data (&r);
        }

      }
    rmrf_file (changeset);

    lim_free (0, changeset);
    lim_free (0, upon_root);
  }

  lim_free (0, upon);
  lim_free (0, dest);
  lim_free (0, default_archive);
  lim_free (0, cache_dir);

  return exit_status;
}




static void
apply_delta_callback (void * vfd, const char * fmt, va_list ap)
{
  int fd;

  fd = (int)(t_ulong)vfd;
  safe_printfmt_va_list (fd, fmt, ap);
  safe_flush (fd);
}


static void 
do_three_way(int chatter_fd, t_uchar * cache_dir, t_uchar * default_archive, t_uchar * upon_root, t_uchar * from_spec, t_uchar * to_spec, int escape_classes)
{
  t_uchar * scratch_dir = tmp_file_name (".", ",,apply-delta-scratch");
  t_uchar * from_path = arch_interpret_delta_path (0, 0, scratch_dir, default_archive, from_spec, cache_dir);
  t_uchar * to_path = arch_interpret_delta_path (0, 0, scratch_dir, default_archive, to_spec, cache_dir);
  arch_merge3 (chatter_fd, upon_root, from_path, to_path, escape_classes);
  rmrf_file (scratch_dir);
}



/* tag: Tom Lord Wed Jun  4 15:40:44 2003 (cmd-deltapatch.c)
 */
