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

#include "rsxnt.h"

static void _rsxnt_gmt2ft(unsigned long time, FILETIME *ft)
{
    SYSTEMTIME st;
    FILETIME ftlocal;

    _rsxnt_gmt2st(&time, &st);
    SystemTimeToFileTime(&st, &ftlocal);
    LocalFileTimeToFileTime(&ftlocal, ft);
}

int __utimes(const char *name, const struct timeval *tvp)
{
    HANDLE hf;
    FILETIME ftaccess, ftmodify;
    SYSTEMTIME st;
    const struct timeval *atime = tvp;
    const struct timeval *mtime = tvp + 1;
    char fname[512];

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

    _rsxnt_truncate_name(fname, name);

    hf = CreateFile(fname, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, NULL);

    if (hf == INVALID_HANDLE_VALUE)
        return _rsxnt_get_last_errno();

    if (atime->tv_sec == 0) {
        GetSystemTime(&st);
        SystemTimeToFileTime(&st, &ftaccess);
    } else {
        _rsxnt_gmt2ft(atime->tv_sec, &ftaccess);
    }
    if (mtime->tv_sec == 0) {
        GetSystemTime(&st);
        SystemTimeToFileTime(&st, &ftmodify);
    } else {
        _rsxnt_gmt2ft(mtime->tv_sec, &ftmodify);
    }
    SetFileTime(hf, NULL, &ftaccess, &ftmodify);
    CloseHandle(hf);

    return 0;
}
