#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include "popfetch.h"
#include "vauth.h"

struct timeval t;
FILE *stream = NULL;
char *hostname = NULL;
extern struct vqpasswd *pw;

int file_init(void)
{
  stream = NULL;

  hostname = getenv("HOSTNAME");
  if (hostname == NULL)
     hostname = DEFAULT_HOSTNAME;

#ifdef FILE_DEBUG
  printf("Hostname: [%s]\n", hostname);
#endif

  return 1;
}

int file_open(void)
{
  int ret = 0;
  char b[MAX_FILE_LEN] = { 0 };

  memset((struct timeval *)&t, 0, sizeof(struct timeval));

  ret = gettimeofday(&t, 0);
  if (ret == -1)
     return 0;

  memset((char *)b, 0, MAX_FILE_LEN);
  snprintf(b, MAX_FILE_LEN, "%s/Maildir/new/%lu.%lu.%s", pw->pw_dir,
           t.tv_sec, t.tv_usec, hostname);

  stream = fopen(b, "w+");
  if (stream == NULL)
     return 0; 

  return 1;
}

int file_close(void)
{
  if (stream)
     fclose(stream);

  stream = NULL;

  return 1;
}

int file_write(char *str)
{
  if (!stream)
     return 0;

  if (str) 
     fprintf(stream, "%s\n", str);
  else
     fprintf(stream, "\n");

  return 1;
}
