/* cmd-changes.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 "tla/libfsutils/rmrf.h"
#include "tla/libarch/namespace.h"
#include "tla/libarch/project-tree.h"
#include "tla/libarch/patch-logs.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/chatter.h"
#include "tla/libarch/archive.h"
#include "tla/libarch/cmdutils.h"
#include "tla/libarch/cmd.h"
#include "tla/libarch/cmd-changes.h"


/* __STDC__ prototypes for static functions */
static void make_changeset_callback (void * ign, char * fmt, va_list ap);



static t_uchar * usage = "[options] [revision] [-- limit...]";
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 and exit.") \
  OP (opt_archive, "A", "archive", 1, \
      "Override `my-default-archive'.") \
  OP (opt_dir, "d", "dir DIR", 1, \
      "Change to DIR first.") \
  OP (opt_output_dir, "o", "output DIR", 1, \
      "Save changeset in DIR (implies --keep).") \
  OP (opt_verbose, "v", "verbose", 0, \
      "Verbose changeset report.") \
  OP (opt_quiet, "q", "quiet", 0, \
      "Suppress progress information") \
  OP (opt_diffs, 0, "diffs", 0, \
      "Include diffs in the output.") \
  OP (opt_keep, "k", "keep", 0, \
      "Don't remove the output directory " \
      "on termination.") \
  OP (opt_hardlinks, 0, "link", 0, \
      "hardlink unchanged files to revision library")\
  OP (opt_unescaped, 0, "unescaped", 0, \
      "show filenames in unescaped form")


t_uchar arch_cmd_changes_help[] = ("report about local changes in a project tree\n"
                                   "Generate a patch report describing the differences between the\n"
                                   "project tree containing DIR (or the current directory) and\n"
                                   "REVISION.\n"
                                   "\n"
                                   "The default patch level for a given version is the latest level for\n"
                                   "which the project tree has a patch.  The default archive and version\n"
                                   "is as printed by \"tla tree-version\".\n");

enum options
{
  OPTS (OPT_ENUM)
};

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



int
arch_cmd_changes (t_uchar * program_name, int argc, char * argv[])
{
  int o;
  struct opt_parsed * option;
  t_uchar * dir = 0;
  t_uchar * output = 0;
  t_uchar * default_archive = 0;
  int diffs = 0;
  int keep = 0;
  int verbose = 0;
  int quiet = 0;
  int exit_status = 0;
  int link_same = 0;
  struct arch_archive * arch = 0;
  int escape_classes = arch_escape_classes;

  dir = str_save (0, ".");

  safe_buffer_fd (1, 0, O_WRONLY, 0);

  option = 0;

  while (1)
    {
      if ((argc > 1) && !str_cmp ("--", argv[1]))
        break;

      o = opt_standard (lim_use_must_malloc, &option, opts, &argc, argv, program_name, usage, version_string, arch_cmd_changes_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_dir:
          {
            lim_free (0, dir);
            dir = str_save (0, option->arg_string);
            break;
          }

        case opt_output_dir:
          {
            lim_free (0, output);
            output = str_save (0, option->arg_string);
            keep = 1;
            break;
          }

        case opt_diffs:
          {
            diffs = 1;
            break;
          }

        case opt_keep:
          {
            keep = 1;
            break;
          }

        case opt_quiet:
          {
            quiet = 1;
            break;
          }

        case opt_verbose:
          {
            verbose = 1;
            break;
          }

	case opt_hardlinks:
	  {
	    link_same = 1;
	    break;
	  }

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

  {
    int argn;
    t_uchar * tree_root = 0;
    t_uchar * fqvsn = 0;
    t_uchar * rvsnspec = 0;
    t_uchar * archive = 0;
    t_uchar * revision = 0;
    t_uchar * log_file = 0;
    t_uchar * tree_arch = 0;
    t_uchar * tree_version = 0;
    t_uchar * latest_log = 0;
    rel_table limits = 0;

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

    tree_root = arch_tree_root (0, dir, 0);

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

    argn = 1;

    if ((argc > argn) && str_cmp (argv[argn], "--"))
      {
        fqvsn = str_save (0, argv[argn]);
        ++argn;
      }
    else
      {
        fqvsn = arch_tree_version (tree_root);
        if (!fqvsn)
          {
            safe_printfmt (2, "%s: no tree-version set\n  tree: %s\n", argv[0], tree_root);
            exit (2);
          }
      }

    tree_arch = arch_parse_package_name (arch_ret_archive, 0, fqvsn);
    tree_version = arch_parse_package_name (arch_ret_non_archive, 0, fqvsn);

    invariant (!!tree_arch);

    if (!arch_valid_package_name (tree_version, arch_no_archive, arch_req_version, 0))
      {
	rvsnspec = str_save (0, fqvsn);
      }
    else
      {
	latest_log = arch_highest_patch_level (tree_root, tree_arch, tree_version);

	if (!latest_log)
	  {
	    safe_printfmt (2, "%s: tree shows no revisions in version\n  tree: %s\n  version: %s\n", argv[0], tree_root, fqvsn);
	    exit (2);
	  }

	rvsnspec = str_alloc_cat_many (0, fqvsn, "--", latest_log, str_end);
      }

    lim_free (0, fqvsn);
    lim_free (0, tree_arch);
    lim_free (0, tree_version);
    lim_free (0, latest_log);

    if (argc > argn)
      {
        if (str_cmp (argv[argn], "--"))
          goto usage_error;

        ++argn;

        if (argc <= argn)
          goto usage_error;

        while (argc > argn)
          {
            rel_add_records (&limits, rel_make_record (argv[argn], 0), 0);
            ++argn;
          }
      }

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

    archive = arch_parse_package_name (arch_ret_archive, default_archive, rvsnspec);
    revision = arch_parse_package_name (arch_ret_non_archive, 0, rvsnspec);

    arch = arch_archive_connect (archive, 0);
    arch_check_for (arch, arch_req_patch_level, revision);
    arch_archive_close (arch);

    if (!output)
      {
        t_uchar * output_basename = 0;

        output_basename = str_alloc_cat_many (0, ",,what-changed.", revision, "--", archive, str_end);
        output = file_name_in_vicinity (0, tree_root, output_basename);
        rmrf_file (output);

        lim_free (0, output_basename);
      }


    /****************************************************************
     * The heart of the matter.
     */
    {
      t_uchar * orig_tree = 0;
      struct arch_make_changeset_report make_report = {0, };
      struct arch_changeset_report report = {0, };
      assoc_table inode_shortcut = 0;

      if (!quiet)
        arch_chatter (1, "* looking for %s/%s to compare with\n", archive, revision);

      orig_tree = arch_find_or_make_local_copy ((quiet ? -1 : 1), tree_root, 0, 0, archive, revision);

      if (!orig_tree)
        {
          safe_printfmt (2, "%s: no local copies to compare to (%s/%s)\n  consider `add-pristine --help'\n",
                         argv[0], archive, revision);
          exit (2);
        }


      if (!quiet)
        arch_chatter (1, "* comparing to %s/%s\n", archive, revision);

      if (!quiet)
        make_report.callback = make_changeset_callback;

      arch_read_inode_sig (0, &inode_shortcut, tree_root, archive, revision);
      arch_make_changeset (&make_report, orig_tree, tree_root, output, arch_unspecified_id_tagging, arch_inventory_unrecognized, limits, inode_shortcut, link_same, escape_classes);
      arch_evaluate_changeset (&report, output);
      exit_status = arch_any_changes (&report);

      if (exit_status && (diffs || verbose))
        {
          if (!quiet)
            safe_printfmt (1, "\n");

          if (verbose)
            /* verbose is a superset of diffs */
            arch_print_changeset (1, &report, diffs, escape_classes);
          else
            arch_print_changeset_diffs (1, &report, escape_classes);
        }

      arch_free_make_changeset_report_data (&make_report);
      arch_free_changeset_report_data (&report);
      lim_free (0, orig_tree);

      /* remove the changeset info unless the user requested it persist */
      if (!keep)
        rmrf_file (output);

      free_assoc_table (inode_shortcut);
    }

    lim_free (0, rvsnspec);
    lim_free (0, tree_root);
    lim_free (0, archive);
    lim_free (0, revision);
    lim_free (0, log_file);
    rel_free_table (limits);
  }


  lim_free (0, dir);
  lim_free (0, output);
  lim_free (0, default_archive);

  exit (exit_status);

  return 0;
}



static void
make_changeset_callback (void * ign, char * fmt, va_list ap)
{
  safe_printfmt_va_list (1, fmt, ap);
  safe_flush (1);
}




/* tag: Tom Lord Fri May 23 14:06:15 2003 (what-changed.c)
 */
