/* project-tree.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/os/errno.h"
#include "hackerlab/vu/safe.h"
#include "hackerlab/fs/cwd.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/char/str.h"
#include "tla/libarch/archive.h"
#include "tla/libarch/namespace.h"
#include "tla/libarch/patch-logs.h"
#include "tla/libarch/changelogs.h"
#include "tla/libarch/inv-ids.h"
#include "tla/libarch/my.h"
#include "tla/libarch/project-tree.h"



/* These must agree about the format version number.
 */
static const int arch_tree_format_vsn = 1;
static const char arch_tree_format_vsn_id[] = "1";
static char arch_tree_format_str[] = "Hackerlab arch project directory, format version 1.";




t_uchar *
arch_tree_format_string (void)
{
  return (t_uchar *)arch_tree_format_str;
}


void
arch_init_tree (const t_uchar * tree_root)
{
  t_uchar * arch_dir = 0;
  t_uchar * arch_vsn_file = 0;
  t_uchar * id_tagging_method_file = 0;
  t_uchar * id_tagging_method_defaults = 0;
  int out_fd;

  arch_dir = file_name_in_vicinity (0, tree_root, "{arch}");
  arch_vsn_file = file_name_in_vicinity (0, arch_dir, ".arch-project-tree");
  id_tagging_method_file = file_name_in_vicinity (0, arch_dir, "=tagging-method");

  safe_mkdir (arch_dir, 0777);
  out_fd = safe_open (arch_vsn_file, O_WRONLY | O_CREAT | O_EXCL, 0666);
  safe_printfmt (out_fd, "%s\n", arch_tree_format_string ());
  safe_close (out_fd);

  id_tagging_method_defaults = arch_default_id_tagging_method_contents (arch_unspecified_id_tagging);
  out_fd = safe_open (id_tagging_method_file, O_WRONLY | O_CREAT | O_EXCL, 0666);
  safe_printfmt (out_fd, "%s", id_tagging_method_defaults);
  safe_close (out_fd);

  lim_free (0, arch_dir);
  lim_free (0, arch_vsn_file);
  lim_free (0, id_tagging_method_defaults);
  lim_free (0, id_tagging_method_file);
}


t_uchar *
arch_tree_root (enum arch_tree_state * state,
                const t_uchar * input_dir,
                int accurate)
{
  int here_fd;
  int errn;
  t_uchar * dir;
  t_uchar * answer;

  answer = 0;

  if (input_dir)
    {
      here_fd = safe_open (".", O_RDONLY, 0);
      safe_chdir (input_dir);
    }

  dir = (t_uchar *)current_working_directory (&errn, 0);
  if (!dir)
    panic ("unable to compute current working directory");

  if (input_dir)
    {
      safe_fchdir (here_fd);
      safe_close (here_fd);
    }

  while (1)
    {
      t_uchar * arch_dir;
      t_uchar * arch_version_file;
      t_uchar * next_dir;
      int found_it;

      arch_dir = file_name_in_vicinity (0, dir, "{arch}");
      arch_version_file = file_name_in_vicinity (0, arch_dir, ".arch-project-tree");

      found_it = (!safe_access (arch_dir, F_OK) && !safe_access (arch_version_file, F_OK));

      lim_free (0, arch_dir);
      lim_free (0, arch_version_file);

      if (found_it)
        {
          answer = str_save (0, dir);
          break;
        }

      if (!str_cmp (dir, "/"))
        break;

      next_dir = file_name_directory_file (0, dir);
      lim_free (0, dir);
      dir = next_dir;
      next_dir = 0;
    }

  if (answer && accurate)
    {
      t_uchar * rc_name;
      t_uchar * cd_name;
      t_uchar * mc_name;

      rc_name = file_name_in_vicinity (0, answer, "{arch}/++resolve-conflicts");
      cd_name = file_name_in_vicinity (0, answer, "{arch}/++commit-definite");
      mc_name = file_name_in_vicinity (0, answer, "{arch}/++mid-commit");

      if (state)
        {
          if (!safe_access (rc_name, F_OK))
            *state = arch_tree_in_resolve_conflicts;
          else if (!safe_access (cd_name, F_OK))
            *state = arch_tree_in_commit_definite;
          else if (!safe_access (mc_name, F_OK))
            *state = arch_tree_in_mid_commit;
          else
            *state = arch_tree_in_ok_state;
        }

      lim_free (0, rc_name);
      lim_free (0, cd_name);
      lim_free (0, mc_name);
    }

  lim_free (0, dir);
  return answer;
}


t_uchar *
arch_tree_ctl_dir (const t_uchar * tree_root)
{
  return file_name_in_vicinity (0, tree_root, "{arch}");
}


int
arch_tree_has_meta_flag (const t_uchar * const tree_root)
{
  t_uchar * ctl_dir = 0;
  t_uchar * meta_file = 0;
  struct stat meta_stat;
  int errn = 0;
  int tree_answer = -69;
  int answer = -69;

  ctl_dir = arch_tree_ctl_dir (tree_root);
  meta_file = file_name_in_vicinity (0, ctl_dir, "=meta");

  if (0 == vu_stat (&errn, meta_file, &meta_stat))
    {
      if (meta_stat.st_size != 0)
        {
          safe_printfmt (2, "illegal ./{arch}/=meta file (non-empty)\n  file: %s\n", meta_file);
          panic ("abort");
        }

      tree_answer = 1;
    }
  else
    {
      if (errn == ENOENT)
        tree_answer = 0;
      else
        panic ("strange i/o error");
    }

  if (tree_answer != 1)
    {
      answer = tree_answer;
    }
  else
    {
      answer = arch_my_allow_full_meta ();

      if (!answer)
        {
          safe_printfmt (2, ("warning: ignoring =meta flag in tree\n"
                             "  to enable full metadata patching (of owner,\n"
                             "  group owner, and 12 permission bits rather\n"
                             "  than 9 when a tree has an =meta file) create\n"
                             "  the empty file:\n"
                             "      ~/.arch-params/metadata-rules.\n"));
        }
    }

  lim_free (0, ctl_dir);
  lim_free (0, meta_file);

  return answer;
}


void
arch_set_tree_version (const t_uchar * tree_root,
                       const t_uchar * archive,
                       const t_uchar * version)
{
  t_uchar * default_version_file = 0;
  t_uchar * fqversion = 0;
  int out_fd;

  invariant (arch_valid_archive_name (archive));
  invariant (arch_valid_package_name (version, arch_no_archive, arch_req_version, 0));

  default_version_file = file_name_in_vicinity (0, tree_root, "{arch}/++default-version");

  fqversion = arch_fully_qualify (archive, version);

  out_fd = safe_open (default_version_file, O_WRONLY | O_CREAT, 0666);

  safe_ftruncate (out_fd, (long)0);
  safe_printfmt (out_fd, "%s\n", fqversion);

  safe_close (out_fd);

  lim_free (0, default_version_file);
  lim_free (0, fqversion);
}


t_uchar *
arch_tree_version (const t_uchar * tree_root)
{
  t_uchar * default_version_file;
  int in_fd;
  t_uchar * file_contents;
  size_t file_contents_len;
  t_uchar * nl;

  default_version_file = file_name_in_vicinity (0, tree_root, "{arch}/++default-version");

  if (safe_access (default_version_file, F_OK))
    {
      lim_free (0, default_version_file);
      return 0;
    }

  in_fd = safe_open (default_version_file, O_RDONLY, 0666);

  file_contents = 0;
  file_contents_len = 0;
  safe_file_to_string (&file_contents, &file_contents_len, in_fd);

  safe_close (in_fd);

  nl = str_chr_index_n (file_contents, file_contents_len, '\n');
  if (nl)
    file_contents_len = nl - file_contents;

  file_contents = lim_realloc (0, file_contents, file_contents_len + 1);
  file_contents[file_contents_len] = 0;

  invariant (arch_valid_package_name (file_contents, arch_req_archive, arch_req_version, 0));

  lim_free (0, default_version_file);

  return file_contents;
}


t_uchar *
arch_try_tree_version (const t_uchar * cmd)
{
  t_uchar * version_spec = 0;
  t_uchar * tree_root = 0;

  tree_root = arch_tree_root (0, ".", 0);

  if (!tree_root)
    {
      safe_printfmt (2, "%s: not in a project tree\n", cmd);
      exit (2);
    }

  version_spec = arch_tree_version (tree_root);

  if (!version_spec)
    {
      safe_printfmt (2, "%s: tree has no default version set\n    tree: %s\n",
                     cmd, tree_root);
      exit (2);
    }

  lim_free (0, tree_root);

  return version_spec;
}



void
arch_start_tree_commit (const t_uchar * tree_root,
                        const t_uchar * log)
{
  int ign;
  t_uchar * mid_commit_file = 0;
  t_uchar * mid_commit_tmp = 0;
  int out_fd;

  mid_commit_file = file_name_in_vicinity (0, tree_root, "{arch}/++mid-commit");
  mid_commit_tmp = file_name_in_vicinity (0, tree_root, "{arch}/,,mid-commit");

  vu_unlink (&ign, mid_commit_tmp);
  vu_unlink (&ign, mid_commit_file);

  out_fd = safe_open (mid_commit_tmp, O_WRONLY | O_CREAT | O_EXCL, 0666);
  safe_printfmt (out_fd, "%s", log);
  safe_close (out_fd);

  safe_rename (mid_commit_tmp, mid_commit_file);

  lim_free (0, mid_commit_file);
}


void
arch_finish_tree_commit (const t_uchar * tree_root,
                         const t_uchar * archive,
                         const t_uchar * revision,
                         const t_uchar * changelog_loc,
                         int const full_meta)
{
  t_uchar * mid_commit_file = 0;
  t_uchar * commit_definite_file = 0;

  mid_commit_file = file_name_in_vicinity (0, tree_root, "{arch}/++mid-commit");
  commit_definite_file = file_name_in_vicinity (0, tree_root, "{arch}/++commit-definite");

  safe_rename (mid_commit_file, commit_definite_file);

  if (changelog_loc)
    {
      const int full_meta = arch_tree_has_meta_flag (tree_root);
      struct stat statb;
      t_uchar * level = 0;
      t_uchar * version = 0;
      t_uchar * changelog_path = 0;
      t_uchar * changelog_dir = 0;
      t_uchar * changelog_tmp = 0;
      mode_t mode;
      int fd;

      level = arch_parse_package_name (arch_ret_patch_level, 0, revision);
      version = arch_parse_package_name (arch_ret_package_version, 0, revision);

      changelog_path = file_name_in_vicinity (0, tree_root, changelog_loc);
      changelog_dir = file_name_directory_file (0, changelog_path);
      changelog_tmp = file_name_in_vicinity (0, changelog_dir, ",,new-changelog");

      safe_stat (changelog_path, &statb);
      if (full_meta)
        {
          mode = statb.st_mode & 07777;
        }
      else
        {
          mode = statb.st_mode & 0777;
        }
        
      fd = safe_open (changelog_tmp, O_WRONLY | O_CREAT | O_TRUNC, mode);
      safe_fchmod (fd, mode);
      if (full_meta)
        safe_fchown (fd, statb.st_uid, statb.st_gid);

      arch_generate_changelog (fd, tree_root, 0, 0, level, commit_definite_file, archive, version);

      safe_close (fd);

      safe_rename (changelog_tmp, changelog_path);

      lim_free (0, level);
      lim_free (0, version);
      lim_free (0, changelog_path);
      lim_free (0, changelog_dir);
      lim_free (0, changelog_tmp);
    }

  arch_copy_to_patch_log (tree_root, archive, revision, commit_definite_file);

  safe_unlink (commit_definite_file);

  lim_free (0, mid_commit_file);
  lim_free (0, commit_definite_file);
}


void
arch_abort_tree_commit (const t_uchar * tree_root,
                        const t_uchar * archive,
                        const t_uchar * revision)
{
  t_uchar * mid_commit_file = 0;

  mid_commit_file = file_name_in_vicinity (0, tree_root, "{arch}/++mid-commit");

  safe_unlink (mid_commit_file);

  lim_free (0, mid_commit_file);
}

t_uchar *
arch_get_tree_fqrevision(const t_uchar *tree_root)
{
  t_uchar * fqvsn = arch_tree_version(tree_root);
  t_uchar * latest_log = 0;
  t_uchar * tree_arch = 0;
  t_uchar * tree_version = 0;
  t_uchar * rvsnspec = 0;
 

  tree_arch = arch_parse_package_name (arch_ret_archive, 0, fqvsn);
  tree_version = arch_parse_package_name (arch_ret_non_archive, 0, fqvsn);
  
  if (!fqvsn)
    {
      safe_printfmt (2, "unable to determine project tree identifier.\n  tree: %s\n",  tree_root);
      return 0;
    }
    
	  latest_log = arch_highest_patch_level (tree_root, tree_arch, tree_version);

      if (!latest_log)
        {
          safe_printfmt (2, "tree shows no revisions in version\n    version: %s\n", fqvsn);
	  
        }
      else
          rvsnspec = str_alloc_cat_many (0, fqvsn, "--", latest_log, str_end);
  

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


  lim_free(0, fqvsn);

  return rvsnspec;
  
}

  
t_uchar * 
arch_get_fqrevision(const t_uchar *fqvsn)
{
  t_uchar * rvsnspec = 0;
  t_uchar * tree_arch = 0;
  t_uchar * tree_version = 0;
  t_uchar * latest_log = 0;

  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
    {

      rel_table archive_levels ;
      struct arch_archive *arch = arch_archive_connect (tree_arch, 0);
      invariant (!!arch);
      archive_levels = arch_archive_revisions (arch, tree_version, 0);
      if (!rel_n_records (archive_levels))
        {
          safe_printfmt (2, "(WEIRD ERROR!) archive has no revisions for version (%s/%s)\n",
                         tree_arch, tree_version);
          exit (1);
        }
      latest_log = str_save (0, rel_peek_str (archive_levels, rel_n_records (archive_levels) - 1, 0));    
      rel_free_table (archive_levels);

      arch_archive_close (arch);

      if (!latest_log)
        {
          safe_printfmt (2, "tree shows no revisions in version\n    version: %s\n", fqvsn);
	  
        }
      else
          rvsnspec = str_alloc_cat_many (0, fqvsn, "--", latest_log, str_end);
    }

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


  return rvsnspec;
}









/* tag: Tom Lord Mon May 12 10:12:38 2003 (project-tree.c)
 */
