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

#include "hackerlab/bugs/panic.h"
#include "hackerlab/mem/alloc-limits.h"
#include "hackerlab/char/str.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/vu/safe.h"
#include "file-utils/libfsutils/tmp-files.h"
#include "file-utils/libfsutils/rmrf.h"
#include "file-utils/libarch/build-revision.h"
#include "file-utils/libarch/pristines.h"
#include "file-utils/libarch/libraries.h"
#include "file-utils/libarch/local-cache.h"



t_uchar *
arch_find_local_copy (t_uchar * tree_root, t_uchar * archive, t_uchar * revision)
{
  t_uchar * answer = 0;

  if (tree_root)
    answer = arch_find_pristine (0, tree_root, archive, revision, arch_any_pristine, arch_tree_and_sibling_pristine_search);

  if (!answer)
    answer = arch_library_find (archive, revision);

  return answer;
}


t_uchar *
arch_find_or_make_local_copy (int chatter_fd, t_uchar * tree_root, struct arch_archive * arch, t_uchar * revision)
{
  t_uchar * answer = 0;

  invariant (!!tree_root);

  answer = arch_find_local_copy (tree_root, arch->name, revision);

  if (!answer)
    {
      t_uchar * tree_dir = 0;
      t_uchar * tmp_path = 0;

      tree_dir = file_name_directory_file (0, tree_root);
      if (!tree_dir)
        tree_dir = str_save (0, ".");

      tmp_path = tmp_file_name (tree_dir, ",,new-pristine");

      rmrf_file (tmp_path);
      safe_mkdir (tmp_path, 0777);

      if (chatter_fd >= 0)
        safe_printfmt (1, "* build pristine tree for %s/%s\n", arch->name, revision);

      arch_build_revision (chatter_fd, tmp_path, arch, arch->name, revision, 0);

      arch_install_pristine (tree_root, arch->name, revision, tmp_path);

      answer = arch_find_local_copy (tree_root, arch->name, revision);

      lim_free (0, tree_dir);
      lim_free (0, tmp_path);
    }

  return answer;
}




/* tag: Tom Lord Fri May 23 14:42:03 2003 (local-cache.c)
 */
