/* stat.c (rsxnt) -- Copyright (c) 1996-1997 Rainer Schnitker */

#include "rsxnt.h"
#include <string.h>

int __stat(const char *name, struct stat *statbuf)
{
    EMXPROCESS *p = _rsxnt_get_process_ptr();
    WIN32_FIND_DATA dta;
    HANDLE fh;
    char fname[512];

    if (_rsxnt_check_npipe (name))
	return _rsxnt_errno(ENOENT);

    _rsxnt_truncate_name (fname, name);

    if (p->bConsoleApp)
	OemToChar(fname, fname);

    memset(statbuf, 0, sizeof (struct stat));

    if ((fh = FindFirstFile((LPSTR) fname, &dta)) == INVALID_HANDLE_VALUE)
    {
        dta.dwFileAttributes = GetFileAttributes(fname);

        if (dta.dwFileAttributes == 0xffffffff)
            return _rsxnt_get_last_errno();

        DosDateTimeToFileTime (32+1, 0, &dta.ftCreationTime);   /* 1.1.1980 */
        DosDateTimeToFileTime (32+1, 0, &dta.ftLastAccessTime); /* 1.1.1980 */
        DosDateTimeToFileTime (32+1, 0, &dta.ftLastWriteTime);  /* 1.1.1980 */
    }
    else
	FindClose(fh);

    /* convert times to gmt */
    _rsxnt_ft2stat(statbuf, &dta.ftCreationTime, &dta.ftLastAccessTime, &dta.ftLastWriteTime);

    statbuf->st_attr = dta.dwFileAttributes & 0x7f;

    /* set mode */
    if (dta.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
	statbuf->st_mode = S_IFDIR | MAKEPERM (S_IREAD|S_IWRITE|S_IEXEC);
	statbuf->st_size = 0;
    } else {
	if (dta.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
	    statbuf->st_mode = MAKEPERM (S_IREAD) | S_IFREG;
	else
	    statbuf->st_mode = MAKEPERM (S_IREAD|S_IWRITE) | S_IFREG;
	statbuf->st_size = dta.nFileSizeLow;
    }

    /* rest is ignored */
    statbuf->st_ino = _rsxnt_stat_ino();
    statbuf->st_nlink = 1;
    statbuf->st_dev = 0;
    statbuf->st_uid = 0;
    statbuf->st_gid = 0;
    statbuf->st_rdev = 0;
    return 0;
}
