/* 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 "hackerlab/cmd/main.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/fs/cwd.h"
#include "hackerlab/vu/vu-dash.h"
#include "tla/libfsutils/tmp-files.h"
#include "tla/libfsutils/rmrf.h"
#include "tla/libfsutils/copy-file.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/copy-project-tree.h"
#include "tla/libarch/archive.h"
#include "tla/libarch/patch-logs.h"
#include "tla/libarch/local-cache.h"
#include "tla/libarch/cmd.h"
#include "tla/libarch/cmd-replay.h"
#include "tla/libarch/cmd-apply-delta.h"
#include "tla/libarch/cmd-undo.h"
#include "tla/libarch/cmd-redo.h"
#include "tla/libarch/cmd-update.h"



static t_uchar * usage = "[options] [version/revision]";
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_dir, "d", "dir DIR", 1, \
      "Update project tree in DIR (default `.')") \
  OP (opt_forward, "N", "forward", 0, \
      "pass the --forward option to `patch'") \
  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_update_help[] = ("update a project tree\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 * default_archive = 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_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_archive:
          {
            lim_free (0, default_archive);
            default_archive = str_save (0, option->arg_string);
            break;
          }

        case opt_forward:
          {
            forward = 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_unescaped:
	  {
	    escape_classes = 0;
	    break;
	  }
        }
    }

  if (argc > 2)
    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);
    }


  {
    t_uchar * upon_root = 0;
    t_uchar * rvsnspec = 0;
    t_uchar * archive = 0;
    t_uchar * version = 0;
    t_uchar * to_level = 0;
    struct arch_archive * arch;
    t_uchar * upon_level = 0;
    rel_table archive_levels = rel_table_nil;
    t_uchar * archive_level = 0;

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

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

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

    if (!rvsnspec)
      {
        rvsnspec = arch_tree_version (upon_root);
        if (!rvsnspec)
          {
            safe_printfmt (2, "%s: tree has no default version (%s)\n",
                           argv[0], upon_root);
            exit (1);
          }
      }

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

    archive = arch_parse_package_name (arch_ret_archive, default_archive, rvsnspec);
    version = arch_parse_package_name (arch_ret_package_version, 0, rvsnspec);

    arch = arch_archive_connect (archive, 0);
    invariant (!!arch);

    upon_level = arch_highest_patch_level (upon_root, archive, 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_root, rvsnspec);
        exit (1);
      }


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

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

    if (arch_valid_package_name (rvsnspec, arch_maybe_archive, arch_req_patch_level, 0))
      {
        int x;
        to_level = arch_parse_package_name (arch_ret_patch_level, 0, rvsnspec);
        for (x = 0; x < rel_n_records (archive_levels); ++x)
          if (!str_cmp (to_level, rel_peek_str (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], archive, version, to_level);
            exit (1);
          }
      }
    else
      {
        to_level = str_save (0, rel_peek_str (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;
        int use_replay_strategy = 1;

        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_root, 0, archive, ancestor_rev, "find-pristine");
        local_latest = arch_find_local_copy (-1, upon_root, 0, archive, 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, rel_peek_str (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;

                this_rev = str_alloc_cat_many (0, version, "--", rel_peek_str (archive_levels, x, 0), str_end);
                arch_revision_type (&type, 0 , arch, this_rev);

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

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

        safe_printfmt (1, "* setting aside local changes temporarily\n");
        safe_flush (1);
        arch_call_cmd (arch_cmd_undo, argv[0], "-A", archive, "-d", dest, ancestor_rev,
                       (escape_classes == 0) ? "--unescaped" : (char*)0, 
		       (char*)0);

        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", "-A", archive, "--dir", dest, version,
                           (escape_classes == 0) ? "--unescaped" : (char*)0, 
			   (char*)0);
          }
        else
          {
            arch_call_cmd (arch_cmd_apply_delta, argv[0], "-A", archive, "--dir", dest, ancestor_rev,
                           latest_rev, (escape_classes == 0) ? "--unescaped" : (char*)0, (char*)0);
          }

        safe_printfmt (1, "* reapplying local changes\n");
        safe_flush (1);

        if (!forward)
          arch_call_cmd (arch_cmd_redo, argv[0], "-d", dest,
                         (escape_classes == 0) ? "--unescaped" : (char*)0, (char*)0);
        else
          arch_call_cmd (arch_cmd_redo, argv[0], "--forward", "-d", dest,
                         (escape_classes == 0) ? "--unescaped" : (char*)0, (char*)0);


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

    lim_free (0, upon_root);
    lim_free (0, rvsnspec);
    lim_free (0, archive);
    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, upon);
  lim_free (0, dest);
  lim_free (0, default_archive);

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

  return exit_status;
}




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