/* cmd-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/changeset-report.h"
#include "tla/libarch/inode-sig.h"
#include "tla/libarch/cmdutils.h"
#include "tla/libarch/cmd.h"
#include "tla/libarch/cmd-delta.h"


/* __STDC__ prototypes for static functions */
static t_uchar * interpret_delta_path (t_uchar ** arch, t_uchar ** rev, t_uchar * scratch_dir, t_uchar * default_archive, t_uchar * spec, t_uchar * cache_dir);
static void delta_callback (void * vfd, char * fmt, va_list ap);



static t_uchar * usage = "[options] (REVISION|TREE)-A (REVISION|TREE)-B [DESTDIR]";
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_cache, 0, "cache DIR", 1, \
      "specify a cache root for pristine copies") \
  OP (opt_no_changeset, "n" , "no-changeset", 0, \
      "do not generate a changeset") \
  OP (opt_diff, 0, "diffs", 0, \
      "print changeset report with diffs (implies -n)") \
  OP (opt_unescaped, 0, "unescaped", 0, \
      "show filenames in unescaped form")


t_uchar arch_cmd_delta_help[] = ("compute a changeset (or diff) between any two trees or revisions\n"
                                 "\n"
                                 "Given (REVISION|TREE)-A and (REVISION|TREE)-B, tla will build a changeset\n"
                                 "that comprises the changes between REVISION-A and REVISION-B\n"
                                 "\n"
                                 "Example:\n"
                                 "  tla delta tla--devo--1.1--patch-6 \\\n"
                                 "            tla--devo--1.1--patch-8 ,,changes\n"
                                 "\n"
                                 "  Will pull patch-6 and patch-8 from tla--devo--1.1 and compute\n"
                                 "  a changeset, which will be saved in a newly created ,,changes\n"
                                 "  directory. If you would like a report instead,\n"
                                 "  append the --diffs option");

enum options
{
  OPTS (OPT_ENUM)
};

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



int
arch_cmd_delta (t_uchar * program_name, int argc, char * argv[])
{
  int o;
  struct opt_parsed * option;
  t_uchar * default_archive = 0;
  t_uchar * cache_dir = 0;
  int no_changeset = 0;
  int report = 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_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_diff:
          {
            report = 1;
            no_changeset = 1;
            break;
          }

        case opt_no_changeset:
          {
            no_changeset = 1;
            break;
          }

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

  if (argc < 3 || argc > 4)
    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 * a_spec;
    t_uchar * b_spec;
    t_uchar * dest = 0;
    t_uchar * scratch_dir = 0;
    t_uchar * orig = 0;
    t_uchar * mod = 0;
    struct arch_make_changeset_report make_report = {0, };
    t_uchar * orig_archive = 0;
    t_uchar * orig_revision = 0;
    assoc_table inode_shortcut = 0;

    a_spec = argv[1];
    b_spec = argv[2];

    if (argc == 4)
      {
        dest = str_save (0, argv[3]);
      }
    else
      {
        dest = tmp_file_name (".", ",,delta");
        rmrf_file (dest);
      }

    scratch_dir = tmp_file_name (".", ",,delta-scratch");

    orig = interpret_delta_path (&orig_archive, &orig_revision, scratch_dir, default_archive, a_spec, cache_dir);
    mod = interpret_delta_path (0, 0, scratch_dir, default_archive, b_spec, cache_dir);

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

    make_report.callback = delta_callback;
    make_report.thunk = (void *)1;

    if (orig_archive)
      {
        arch_read_inode_sig (0, &inode_shortcut, mod, orig_archive, orig_revision);
      }

    arch_make_changeset (&make_report, orig, mod, dest, arch_unspecified_id_tagging, arch_inventory_unrecognized, 0, inode_shortcut, 0, escape_classes);

    if (report)
      {
        struct arch_changeset_report r = {0, };

        safe_printfmt (1, "* changeset report\n");
        arch_evaluate_changeset (&r, dest);
        arch_print_changeset (1, &r, 1, escape_classes);

        arch_free_changeset_report_data (&r);
      }

    rmrf_file (scratch_dir);

    if (no_changeset)
      rmrf_file (dest);
    else
      safe_printfmt (1, "* changeset: %s\n", dest);

    lim_free (0, dest);
    lim_free (0, scratch_dir);
    lim_free (0, orig);
    lim_free (0, mod);
    lim_free (0, orig_archive);
    lim_free (0, orig_revision);
    free_assoc_table (inode_shortcut);
    arch_free_make_changeset_report_data (&make_report);
  }

  lim_free (0, default_archive);

  return 0;
}




static t_uchar *
interpret_delta_path (t_uchar ** arch, t_uchar ** rev, t_uchar * scratch_dir, t_uchar * default_archive, t_uchar * spec, t_uchar * cache_dir)
{
  t_uchar * answer = 0;

  if (arch_valid_package_name (spec, arch_maybe_archive, arch_req_patch_level, 0))
    {
      t_uchar * archive = 0;
      t_uchar * revision = 0;
      struct arch_archive *arch_struct = 0;

      archive = arch_parse_package_name (arch_ret_archive, default_archive, spec);
      revision = arch_parse_package_name (arch_ret_non_archive, 0, spec);
      
      arch_struct = arch_archive_connect (archive, 0);
      arch_check_for (arch_struct, arch_req_patch_level, revision);

      safe_printfmt (1, "* finding or making %s\n", spec);

      answer = arch_find_or_make_tmp_local_copy (1, scratch_dir, 0, cache_dir, arch_struct, archive, revision);
      arch_archive_close (arch_struct);

      if (arch)
        *arch = archive;
      else
        lim_free (0, archive);

      if (rev)
        *rev = revision;
      else
        lim_free (0, revision);
    }
  else if (arch_valid_patch_level_name (spec))
    {
      t_uchar * archive = 0;
      t_uchar * revision = 0;
      t_uchar * fqvsn = 0;
      t_uchar * tree_version = 0;
      t_uchar * tree_root = 0;
      
      tree_root = arch_tree_root (0, ".", 0);

      if (!tree_root)
        {
          safe_printfmt (2, "tla delta: not in a project tree\n  dir: %s\n", directory_as_cwd ("."));
          exit (2);
        }

      fqvsn = arch_tree_version (tree_root);
      if (!fqvsn)
	{
	  safe_printfmt (2, "tla delta: no tree-version set\n  tree: %s\n", tree_root);
	  exit (2);
	}
      
      archive = arch_parse_package_name (arch_ret_archive, 0, fqvsn);
      tree_version = arch_parse_package_name (arch_ret_non_archive, 0, fqvsn);
      revision = str_alloc_cat_many (0, tree_version, "--", spec, str_end);

      safe_printfmt (1, "* finding or making %s\n", spec);
      safe_flush (1);

      answer = arch_find_or_make_tmp_local_copy (1, scratch_dir, 0, cache_dir, 0, archive, revision);

      if (arch)
        *arch = archive;
      else
        lim_free (0, archive);

      if (rev)
        *rev = revision;
      else
        lim_free (0, revision);

      lim_free (0, fqvsn);
      lim_free (0, tree_version);
      lim_free (0, tree_root);
    }
  else
    {
      arch_check_directory (spec, 0);
      answer = directory_as_cwd (spec);
    }

  return answer;
}


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

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





/* tag: Tom Lord Wed Jun  4 13:44:58 2003 (cmd-revdelta.c)
 */
