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

#include "hackerlab/fs/file-names.h"
#include "hackerlab/char/str.h"
#include "hackerlab/vu/safe.h"
#include "hackerlab/char/pika-escaping-utils.h"
#include "tla/libarch/diffs.h"
#include "tla/libarch/cached-inventory.h"
#include "tla/libarch/local-cache.h"
#include "tla/libarch/inv-ids.h"
#include "tla/libarch/file-diffs.h"



int
arch_file_get_or_diff (int out_fd, t_uchar * tree_root, t_uchar * mod_loc, t_uchar * archive, t_uchar * revision, int diff, int new_is_null, int escape_classes)
{
  t_uchar * mod_path = 0;
  t_uchar * id = 0;
  t_uchar * cached_tree = 0;
  rel_table index = 0;
  int x;
  t_uchar * orig_loc = 0;
  t_uchar * orig_path = 0;
  int status = 2;

  mod_path = file_name_in_vicinity (0, tree_root, mod_loc);
  safe_chdir (tree_root);
  id = arch_inventory_id (arch_unspecified_id_tagging, 0, mod_loc, 0, 0, 0);

  cached_tree = arch_find_or_make_local_copy (out_fd, ".", 0, 0, archive, revision);
  if (!cached_tree)
    {
      safe_printfmt (2, "arch_file_diffs: tree not found in cache for comparison -- %s/%s\n", archive, revision);
    }

  index = arch_cached_index (cached_tree);

  for (x = 0; x < rel_n_records (index); ++x)
    {
      if (!str_cmp (id, index[x][1]))
        {
          orig_loc = str_save (0, index[x][0]);
          orig_path = file_name_in_vicinity (0, cached_tree, index[x][0]);
          break;
        }
    }

  if (!orig_path && !new_is_null)
    {
      safe_printfmt (out_fd, "new file (not present in %s/%s)\n", archive, revision);
      status = 1;
    }
  else
    {
      if (diff)
        {
          status = arch_invoke_diff (out_fd, orig_path ? orig_path : (t_uchar *)"/dev/null", orig_loc, mod_path, mod_loc, 0, 0);
        }
      else
        {
          t_uchar * escaped_tmp;
          escaped_tmp = pika_save_escape_iso8859_1 (0, 0, escape_classes, orig_path ? orig_path : (t_uchar *)"/dev/null");
          safe_printfmt (out_fd, "%s\n", escaped_tmp);
          status = 0;
          lim_free (0, escaped_tmp);
        }
    }


  lim_free (0, mod_path);
  lim_free (0, id);
  lim_free (0, cached_tree);
  rel_free_table (index);
  lim_free (0, orig_loc);
  lim_free (0, orig_path);

  return status;
}



/* tag: Tom Lord Fri May 30 20:19:00 2003 (file-diffs.c)
 */
