                                                          
/* setdate.c - Set file timestamp to match RT-11 date */
/* Copyright 1994 Syndesis Corporation, by John Foust <jfoust@threedee.com> */
/* March 17, 1998 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <time.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/utime.h>

#include "diskdecl.h"

#include "rt11decl.h"
#include "rt11vars.h"


/* Set the filesystem timestamp to agree with the RT-11 data */

void rtSetTimeStamp( char *filename, rtFileEntry *eachEntry )
{
struct _utimbuf timebuf;
struct tm rtTime;
time_t fileTime;
int result;
int day;
int month;
int year;


    year  = (eachEntry->date & 0x1F) + 72;
    day   = (eachEntry->date >> 5)  & 0x1F;
    month = (eachEntry->date >> 10) & 0x1F;

    /* Safety */
    if (month < 1 || month > 12) {
        month = 1;
    }
    if (day < 1 || day > 31) {
        day = 1;
    }
    if (year < 72 || year > 103) {
        year = 72;
    }

    /* All translated files made at noon */
    rtTime.tm_sec = 0;   /* seconds after the minute - [0,59] */
    rtTime.tm_min = 0;   /* minutes after the hour - [0,59] */
    rtTime.tm_hour = 12; /* hours since midnight - [0,23] */

    /* On the date they were made under RT-11 */
    /* day of the month - [1,31] */
    rtTime.tm_mday = day;
    
    /* months since January - [0,11] */
    rtTime.tm_mon = month - 1;

    /* Year (current year minus 1900) */
    rtTime.tm_year = year;

    /* Leave these fields zero */
    rtTime.tm_wday = 0; /* days since Sunday - [0,6] */
    rtTime.tm_yday = 0; /* days since January 1 - [0,365] */

    /* Positive if daylight saving time is in effect; 
    0 if daylight saving time is not in effect; 
    negative if status of daylight saving time is unknown. */
    rtTime.tm_isdst = -1;   /* daylight savings time flag */

    /* Debug */
    /* printf( "rtTime %s", asctime( &rtTime ) ); */

    /* Convert the 'struct tm' to a 'time_t' */
    fileTime = mktime( &rtTime );
    if (fileTime == (time_t) -1) {
        printf( "mktime failed\n" ) /* failed */;
    }

    /* Make create and modification dates the same */
    timebuf.actime = fileTime;
    timebuf.modtime = fileTime;

    /* Set the time on the file */
    result = _utime( filename, &timebuf );
    if (result == -1) {
        printf( "_futime '%s' failed, errno %d\n", filename, errno );
    }
}

