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

#include "hackerlab/os/time.h"
#include "hackerlab/os/sys/types.h"
#include "hackerlab/os/unistd.h"
#include "hackerlab/fmt/cvt.h"
#include "hackerlab/char/str.h"
#include "hackerlab/char/str-many.h"
#include "hackerlab/vu/safe.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/vu/safe.h"
#include "tla/libfsutils/tmp-files.h"



static int seq = 0;

t_uchar *
tmp_file_name (t_uchar * dir, t_uchar * basename)
{
  time_t now;
  pid_t pid;
  t_uchar now_str[32];
  t_uchar pid_str[32];
  t_uchar seq_str[32];
  t_uchar * path;

  now = time (0);
  pid = getpid ();
  ++seq;

  cvt_ulong_to_decimal (now_str, (unsigned long)now);
  cvt_ulong_to_decimal (pid_str, (unsigned long)pid);
  cvt_ulong_to_decimal (seq_str, (unsigned long)seq);

  path = file_name_in_vicinity (0, dir, basename);
  path = str_realloc_cat_many (0, path, ".", now_str, ".", pid_str, ".", seq_str, str_end);

  return path;
}


t_uchar *
tmp_seq_file (t_uchar * dir, t_uchar * basename)
{
  int seq = 0;

  while (1)
    {
      t_uchar seq_str[32];
      t_uchar * path = 0;

      cvt_ulong_to_decimal (seq_str, (unsigned long)seq);

      path = file_name_in_vicinity (0, dir, basename);
      path = str_realloc_cat_many (0, path, ".", seq_str, str_end);

      if (safe_access (path, F_OK))
        return path;

      ++seq;
      lim_free (0, path);
      path = 0;
    }
}






/* tag: Tom Lord Thu May 15 23:22:25 2003 (tmp-files.c)
 */
