/* $Id: libdeps.c,v 1.2 2008/10/31 22:01:27 kiesling Exp $ */

/*
  This file is part of ctalk.
  Copyright  2005-2008 Robert Kiesling, ctalk@ctalklang.org.
  Permission is granted to copy this software provided that this copyright 
  notice is included in all source code modules.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software Foundation, 
  Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <stdio.h>
#include <string.h>
#include "object.h"
#include "message.h"
#include "ctalk.h"
#include "classlib.h"

extern char *classlibdir;      /* Declared in main.c */
extern char *libcachedir;

/*
 *  The format of ctpp_ofn_path is generally something like
 *  /tmp/Object.ctpp.<id>
 */
int cache_ctpp_output_file (char *ctpp_ofn_path) {
  char lib_cache_path[FILENAME_MAX];
  char buf[FILENAME_MAX], fn[FILENAME_MAX];
  char *ctpp_ofn_lastdot, *ctpp_ofn_lastslash;

  strcpy (buf, ctpp_ofn_path);
  
  if ((ctpp_ofn_lastdot = rindex (buf, '.')) != NULL)
    *ctpp_ofn_lastdot = '\0';

  if ((ctpp_ofn_lastslash = rindex (buf, '/')) != NULL) {
    strcpy (fn, ctpp_ofn_lastslash + 1);
  }  else {
    strcpy (fn, buf);
  }
    
  sprintf (lib_cache_path, "%s/%s", libcachedir, fn);
  copy_file (ctpp_ofn_path, lib_cache_path);

  return SUCCESS;
}

int ctpp_deps_updated (char *class_path) {
  char fn[FILENAME_MAX];
  char lib_cache_path[FILENAME_MAX];
  char *lastslash;
  int lib_mtime, cache_mtime;

  if ((lastslash = rindex (class_path, '/')) != NULL) {
    strcpy (fn, lastslash + 1);
  } else {
    strcpy (fn, class_path);
  }

  sprintf (lib_cache_path, "%s/%s.ctpp", libcachedir, fn);

  if (!file_exists (lib_cache_path))
    return TRUE;

  lib_mtime = file_mtime (class_path);
  cache_mtime = file_mtime (lib_cache_path);
  if ((lib_mtime != ERROR) && 
      (cache_mtime != ERROR) && 
      (lib_mtime > cache_mtime))
    return TRUE;
      
  return FALSE;
}

char *ctpp_cache_path (char *classname) {
  static char buf[FILENAME_MAX];
  sprintf (buf, "%s/%s.ctpp", libcachedir, classname);
  return buf;
}
