/* this is an implementation of the Unix "stat" library routine
   for the Amiga computer and Lattice compiler.
   November '89 Eric Green.
*/

#include "stat.h"

#include <libraries/dos.h>
#include <libraries/dosextens.h>

#ifdef LATTICE
#include <proto/dos.h>
#else
  struct FileLock *Lock();
  long Examine();
  void UnLock();
#endif

#include <exec/memory.h>

#ifdef LATTICE
#include <proto/exec.h>
#else
  struct FileInfoBlock *AllocMem();
  void FreeMem();
#endif

#include <errno.h>

#ifdef LATTICE
#include <dos.h>   /* for getft() */
#endif

int stat(name,buf)
  char *name;
  register struct stat *buf;
{
    register struct FileLock *f;
    register struct FileInfoBlock *fib;
    register long result;

    f = Lock(name,SHARED_LOCK);
    if (f==0) {
        /* return an io error. */
        errno = ENOENT;  /* doesn't exist. */
        return -1;
    }

    fib = AllocMem(sizeof(struct FileInfoBlock),MEMF_CLEAR|MEMF_PUBLIC);
    result = Examine(f,fib);
/* result might be nothing -- in which case our FIB is blank. If so,
   well, what more can we do here? Why are they Examine()'ing a
   SER: device anyhow?
*/

    UnLock(f);  /* clean up that, at least. */

    buf->st_rdev = buf->st_dev = DeviceProc(name);
    buf->st_ino = fib->fib_DiskKey;  /* AmigaDOS equivalent. */

    buf->st_mode = (fib->fib_DirEntryType > 0) ? S_IFDIR : S_IFREG;

    if (fib->fib_Protection & FIBF_READ)
        buf->st_mode |= S_IREAD;
    else if (fib->fib_Protection & FIBF_WRITE)
        buf->st_mode |= S_IWRITE;
    else if (fib->fib_Protection & FIBF_EXECUTE)
        buf->st_mode |= S_IEXEC;
    buf->st_size = fib->fib_Size;
    FreeMem(fib,sizeof(struct FileInfoBlock));

/* what follows is a LATTICE call. Otherwise, time left blank, now: */
#ifdef LATTICE
    buf->st_atime =
    buf->st_mtime =
    buf->st_ctime = getft(name);
#endif

    return 0;
}

