#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <io.h>
#include <windows.h>

typedef struct info{
	char *str;   /*pattern identifying value on cmd line option*/
	char *val;
	int len;
	char *w3c_id;
}info;

#define cmd_line_params 8
info id[cmd_line_params] = {
	{"logto=",    0, 6, 0},            /* file to write log into, create value or get from cmd line from surgeftp */
	{"date=",     0, 5, "x-date"},     /* create value */
	{"time=",     0, 5, "x-time"},     /* create value */
	{"userip=",   0, 7, "c-ip"},       /*value sent by surgeftp*/
	{"transfer=", 0, 9, "cs-method"},  /*value sent by surgeftp*/
	{"user=",     0, 5, "c-user"},     /*value sent by surgeftp*/
	{"bytes=",    0, 6, "x-file_size"},/*value sent by surgeftp*/
	{"file=",     0, 5, "x-file_name"},/*value sent by surgeftp*/
};
enum{LOGTO,XDATE,XTIME,USERIP,TRANSFER,USER,XBYTES,FILENAME};



#include <errno.h>
#include <io.h>
#include <sys/locking.h>



#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif



static char *lock_style = "NT";
int my_flock(int fd){
	if (0 == _locking(fd,_LK_LOCK,4L))
		return TRUE;  /* 10 attemps at 1 sec intervals */
	return FALSE;
}
void  my_unflock(int fd){
	_locking(fd,_LK_UNLCK,4L);
}
FILE *myfopen(char *file, char *mode){
	int i;
	FILE *F;
	for (i=0;i<10;i++){
		F = fopen(file,mode);
		if (F != NULL) return F;
		Sleep(1000);
	}
	return 0;
}




int main(int argc, char *argv[]){
	int i, j;
	FILE *f;
	time_t t_now;
	struct tm *now;
	char now_date[30], now_time[30];
	for (i=1;i<argc;i++){
		for (j=1;j<cmd_line_params;j++){
			if (strncmp(argv[i], id[j].str, id[j].len) == 0) 
				id[j].val = argv[i] + id[j].len;
		}
	}
	if (strcmp(id[TRANSFER].val, "downloaded") ==0) 
		id[TRANSFER].val = "GET"; 
	else 
		id[TRANSFER].val = "PUT";
	if (id[LOGTO].val == 0) id[LOGTO].val = "ftp_w3c.log";
	t_now = time(NULL);
	now = localtime(&t_now);
	_snprintf(now_date, 28, "%4d-%02d-%02d", now->tm_year+1900, now->tm_mon+1, now->tm_mday);
	_snprintf(now_time, 28, "%02d:%02d:%02d", now->tm_hour, now->tm_min, now->tm_sec);
	id[XDATE].val = now_date;
	id[XTIME].val = now_time;
	f = myfopen(id[LOGTO].val, "a");
	if (f != 0 && my_flock(fileno(f))){
		fseek(f, 0, SEEK_END);
		if (ftell(f)==0) {
			fprintf(f, "#Version: 1.0\n#Software: SurgeFTP\n#Fields: ");
			for (i=0;i<cmd_line_params;i++)
				if (id[i].w3c_id != 0) fprintf(f, "%s%s", (id[i].w3c_id, (1==cmd_line_params-1)?"\n":" "));
		}
		for (i=0;i<cmd_line_params;i++){
			if (id[i].w3c_id != 0) fprintf(f, "%s%s", id[i].val, (i==cmd_line_params-1)?"\n":" ");
		}
		fclose(f);
	}
	return 0;
}
