/*
 * This is a fixed version of lstat() from AmiTCP 3.0 beta 2.
 * Author is Pekka Pessi <Pekka.Pessi@hut.fi> and the following
 * copyright notice applies:
 *
 * Copyright © 1993,1994 AmiTCP/IP Group, <amitcp-group@hut.fi>
 *             Helsinki University of Technology, Finland.
 *             All rights reserved.
 */

#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <ios1.h>
#include <proto/dos.h>
#include <proto/utility.h>

#include "AmiTCP:src/netlib/netlib.h"
#include "AmiTCP:src/netlib/fibex.h"
#include "config.h"

int lstat(const char *name, struct stat *st)
{
  /* Cannot lock - do examine via Examine()/ExNext() */
  int rc = -1;
  char *cname;

  if (st == NULL || ((1 & (long)st) == 1)) {
    errno = EFAULT;
    return -1;
  }

  cname = malloc(strlen(name) + 1);

  if (cname) {
    BPTR lock;
    char *pp = PathPart(strcpy(cname, name));
    *pp = '\0';

    if (lock = Lock(cname, SHARED_LOCK)) {
      pp = FilePart(name);
      
      if (Examine(lock, __dostat_fib)) {
	while (ExNext(lock, __dostat_fib)) {
	  if (Stricmp(pp, __dostat_fib->fib_FileName) == 0) {
	    __dostat(__dostat_fib, st);
	    st->st_dev = (dev_t)((struct FileLock *)BADDR(lock))->fl_Task;
	    rc = 0;
	    break;
	  }
	}
      } 
      if (rc != 0)
	errno = ENOENT;

      /* !!! FIX !!!
       * This UnLock() was missing,
       * fixed 08/94 by Blaz Zupan
       */
      UnLock(lock);

    } else {
      set_errno(IoErr());
    }

    free(cname);
  } else {
    errno = ENOMEM;
  }

  return rc;
}
