/* cmd-update.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 "po/gettext.h"
#include "hackerlab/bugs/exception.h"
#include "hackerlab/cmd/main.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/fs/cwd.h"
#include "hackerlab/vu/vu-dash.h"
#include "libfsutils/tmp-files.h"
#include "libfsutils/rmrf.h"
#include "libfsutils/copy-file.h"
#include "libfsutils/dir-as-cwd.h"
#include "libarch/archive.h"
#include "libarch/apply-changeset.h"
#include "libarch/conflict-handling.h"
#include "libarch/copy-project-tree.h"
#include "libarch/inode-sig.h"
#include "libarch/local-cache.h"
#include "libarch/my.h"
#include "libarch/namespace.h"
#include "libarch/patch-logs.h"
#include "libarch/project-tree.h"
#include "libarch/proj-tree-lint.h"
#include "libarch/chatter.h"
#include "libarch/make-changeset.h"
#include "libarch/changeset-report.h"
#include "commands/cmd.h"
#include "commands/cmdutils.h"
#include "commands/replay.h"
#include "commands/apply-delta.h"
#include "commands/undo.h"
#include "commands/redo.h"
#include "commands/update.h"
#include "commands/version.h"



static t_uchar * usage = N_("[options] [version/revision]");

#define OPTS(OP) \
  OP (opt_help_msg, "h", "help", 0, \
      N_("Display a help message and exit.")) \
  OP (opt_long_help, "H", 0, 0, \
      N_("Display a verbose help message and exit.")) \
  OP (opt_version, "V", "version", 0, \
      N_("Display a release identifier string\n" \
      "and exit.")) \
  OP (opt_dir, "d", "dir DIR", 1, \
      N_("Update project tree in DIR (default `.')")) \
  OP (opt_dest, 0, "dest DEST", 1, \
      N_("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, \
      N_("show filenames in unescaped form"))


t_uchar arch_cmd_update_help[] = N_("update a project tree to reflect recent archived changes\n"

                                  "Update a project tree by getting the latest revision of VERSION (or the\n"
                                  "default version of the project tree) and then applying a patch set of\n"
                                  "the differences between the project tree and the highest revision with\n"
                                  "which it is up-to-date.\n"
                                  "\n"
                                  "If the merge involves conflicts, a warning message is printed, and the\n"
                                  "new project tree will contain \".rej\" files.\n");

enum options
{
  OPTS (OPT_ENUM)
};

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



int
arch_cmd_update (t_uchar * program_name, int argc, char * argv[])
{
  int o;
  struct opt_parsed * option;
  t_uchar * upon = 0;
  t_uchar * dest = 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, libarch_version_string, arch_cmd_update_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_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_unescaped:
	  {
	    escape_classes = 0;
	    break;
	  }
        }
    }

  if (argc > 2)
    goto usage_error;

  {
    arch_project_tree_t * upon_tree;
    t_uchar * rvsnspec = 0;
    t_uchar * version = 0;
    t_uchar * to_level = 0;
    t_uchar * package = 0;
    struct arch_archive * arch;
    t_uchar * upon_level = 0;
    rel_table archive_levels = 0;
    t_uchar * archive_level = 0;

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

    upon_tree = arch_project_tree_new (talloc_context, upon);

    if (!upon_tree->root)
      {
        safe_printfmt (2, "%s: dir not in a project tree (%s)\n",
                       argv[0], upon);
        exit (1);
      }

    arch_tree_ensure_no_conflicts (upon_tree);

    if (argc > 1)
      rvsnspec = str_save (0, argv[1]);

    if (!rvsnspec)
      {
        rvsnspec = str_save(0, upon_tree->fqversion);
        if (!rvsnspec)
          {
            safe_printfmt (2, "%s: tree has no default version (%s)\n",
                           argv[0], upon_tree->root);
            exit (1);
          }
      }

    arch_project_tree_check_name (upon_tree, &arch, &package, rvsnspec);
    if (!arch)
      {
	safe_printfmt (2, "Failed to connect to archive %s\n", rvsnspec);
	exit(1);
      }

    if (!arch_valid_package_name (package, arch_req_archive, arch_req_version, 1))
      {
        safe_printfmt (2, "%s: illegal version name (%s)\n", argv[0], package);
        exit (1);
      }

    version = arch_parse_package_name (arch_ret_package_version, 0, package);

    upon_level = arch_highest_patch_level (upon_tree->root, arch->official_name, version);

    if (!upon_level)
      {
        safe_printfmt (2, "%s: tree has no common history with version\n    tree: %s\n    version: %s\n",
                       argv[0], upon_tree->root, package);
        exit (1);
      }

    archive_levels = arch_archive_revisions (arch, version, 0);
    if (rel_n_records (archive_levels) == 0)
      {
        safe_printfmt (2, "%s: (WEIRD ERROR!) archive has no revisions for version (%s/%s)\n",
                       argv[0], arch->official_name, version);
        exit (1);
      }

    if (dest)
      {
        safe_printfmt (1, "* copying %s to %s\n", upon_tree->root, dest);
        safe_flush (1);
        arch_copy_project_tree (upon_tree, dest, 1, 1);
      }
    else
      dest = str_save (0, upon_tree->root);

    if (arch_valid_package_name (package, arch_maybe_archive, arch_req_patch_level, 0))
      {
        int x;
        to_level = arch_parse_package_name (arch_ret_patch_level, 0, package);
        for (x = 0; x < rel_n_records (archive_levels); ++x)
          if (!str_cmp (to_level, archive_levels[x][0]))
            break;
        if (x == rel_n_records (archive_levels))
          {
            safe_printfmt (2, "%s: version (in archive) does not have level (%s/%s--%s)\n", argv[0], arch->official_name, version, to_level);
            exit (1);
          }
      }
    else
      {
        to_level = str_save (0, archive_levels[rel_n_records (archive_levels) - 1][0]);
      }


    if (!str_cmp (upon_level, to_level))
      {
        safe_printfmt (1, "* tree is already up to date\n");
        safe_flush (1);
      }
    else
      {
        t_uchar * ancestor_rev = 0;
        t_uchar * latest_rev = 0;
        t_uchar * local_ancestor = 0;
        t_uchar * local_latest = 0;
	t_uchar * local_changes_changeset;
        int use_replay_strategy = 1;
	int local_changes = 0;

        ancestor_rev = str_alloc_cat_many (0, version, "--", upon_level, str_end);
        latest_rev = str_alloc_cat_many (0, version, "--", to_level, str_end);

        local_ancestor = arch_find_local_copy (-1, upon_tree, 0, arch->official_name, ancestor_rev, "find-pristine");
        local_latest = arch_find_local_copy (-1, upon_tree, 0, arch->official_name, latest_rev, "find-pristine");

        if (local_ancestor && local_latest)
          use_replay_strategy = 0;

        if (use_replay_strategy)
          {
            enum arch_revision_type type;
            int x;

            /* are we sure we really can?
             */

            for (x = 0; x < rel_n_records (archive_levels); ++x)
              if (!str_cmp (upon_level, archive_levels[x][0]))
                break;
            invariant (x < rel_n_records (archive_levels));

            while (use_replay_strategy && (x < rel_n_records (archive_levels)))
              {
                t_uchar * this_rev = 0;
                arch_patch_id * this_patch;

                this_rev = str_alloc_cat_many (0, version, "--", archive_levels[x][0], str_end);
                this_patch = arch_patch_id_new_archive (arch->official_name, this_rev);
                arch_revision_type (&type, NULL , NULL, arch, this_patch);
                talloc_free (this_patch);

                if (type != arch_simple_revision)
                  {
                    use_replay_strategy = 0;
                    break;
                  }

                lim_free (0, this_rev);
                ++x;
              }
          }

        safe_printfmt (1, "* checking tree for local changes\n");
        safe_flush (1);
	if ((local_changes_changeset = arch_any_local_changes (program_name, upon_tree)))
	  {
	    /* apply the changset in reverse */
	    struct arch_apply_changeset_report * apply_report;
	    arch_chatter (1, _("* temporarily reverting local changes\n"));
	    safe_flush (1);
	    apply_report = arch_apply_changeset (local_changes_changeset, talloc_context, upon_tree, arch_unspecified_id_tagging, arch_inventory_unrecognized, 1, 0, escape_classes, NULL, NULL);
	    local_changes = 1;
	    talloc_free (apply_report);
	  }
	    
        safe_printfmt (1, "* updating for new patches in archive\n");
        safe_flush (1);
        if (use_replay_strategy)
          {
            /* could be fancy here and binary search for local copies :-)
             */
            arch_call_cmd (arch_cmd_replay, argv[0], "--new", "--dir", dest, version,
                           (escape_classes == 0) ? "--unescaped" : 0, 0);
          }
        else
          {
	    arch_project_tree_t * from_tree = arch_find_or_make_local_tree_copy (1, upon_tree, NULL, arch, arch->official_name, ancestor_rev);
	    arch_project_tree_t * to_tree = arch_find_or_make_local_tree_copy (1, upon_tree, NULL, arch, arch->official_name, latest_rev);
	    struct arch_make_changeset_report make_report = {0, };
	    assoc_table inode_shortcut = NULL;
	    t_uchar * changeset;
            struct arch_apply_changeset_report * r;

	    arch_read_inode_sig_ids (0, &inode_shortcut, to_tree->root, arch->official_name, ancestor_rev);
	    changeset = talloc_tmp_file_name (talloc_context, ".", ",,delta");
	    rmrf_file (changeset);

	    arch_make_changeset (&make_report, from_tree, to_tree, changeset, arch_unspecified_id_tagging, arch_inventory_unrecognized, 0, inode_shortcut, 0, 0);
	    arch_free_make_changeset_report_data (&make_report);
	    
            safe_printfmt (1, "* applying changeset\n");
            
            r = arch_apply_changeset (changeset, changeset, upon_tree,
                                  arch_unspecified_id_tagging,
                                  arch_inventory_unrecognized,
                                  0, 0, escape_classes,
				  apply_print_callback,
				  (void *)1);
            
	    rmrf_file (changeset);
	    free_assoc_table (inode_shortcut);
	    arch_project_tree_delete (from_tree);
	    arch_project_tree_delete (to_tree);
	    talloc_free (changeset);
          }

	if (local_changes)
	  {
	    struct arch_apply_changeset_report * apply_report;
	    safe_printfmt (1, "* reapplying local changes\n");
	    safe_flush (1);
	    apply_report = arch_apply_changeset (local_changes_changeset, talloc_context, upon_tree, arch_unspecified_id_tagging, arch_inventory_unrecognized, 0, 0, escape_classes, NULL, NULL);
	    rmrf_file (local_changes_changeset);
	    lim_free (0, local_changes_changeset);
	    talloc_free (apply_report);
	  }

        lim_free (0, ancestor_rev);
        lim_free (0, latest_rev);
      }

    arch_project_tree_delete (upon_tree);
    lim_free (0, rvsnspec);
    lim_free (0, version);
    lim_free (0, to_level);
    arch_archive_close (arch);
    lim_free (0, upon_level);
    rel_free_table (archive_levels);
    lim_free (0, archive_level);
    lim_free (0, package);
  }

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

  if (exit_status)
    {
      safe_printfmt (2, "\nupdate: conflicts occurred during update\n");
    }

  return exit_status;
}




/* tag: Tom Lord Wed Jun  4 22:39:12 2003 (cmd-update.c)
 */


syntax highlighted by Code2HTML, v. 0.9.1