/* Balsa E-Mail Client
 * Copyright (C) 1997 Jay Painter
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
#include <stdlib.h>  
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <gtk/gtk.h>
#include "postoffice.h"
#include "mailbox.h"



PostOffice *postofficeX = NULL;


void
postoffice_init ()
{
  if (!postofficeX)
    postofficeX = postoffice_new ();
}


/*
 * postoffice_new -- this is actually a singleton, even though it looks
 * like it's set up for multiple copies.  I did this just because I could, 
 * mabe I'll have to use it some day.  It actually might be useful for 
 * a setuid system so that someone could check the e-mail of another user
 * on the same system.
 */
PostOffice *
postoffice_new ()
{
  GList *list;
  struct passwd *pw;
  DIR *dp;
  struct dirent *d;
  struct stat st;
  char filename[PATH_MAX+1];

  Mailbox *mailbox;
  PostOffice *postoffice;

  postoffice = g_malloc (sizeof (PostOffice));
  postoffice->name = NULL;
  postoffice->dir = NULL;
  postoffice->maildir = NULL;
  postoffice->open = NULL;
  postoffice->mailbox_list = NULL;


  /*
   * Now it's time to get our hands dirty -- no more just messing with 
   * data structures.  Now we have to deal with nifty UNIX stuff.
   */

  pw = getpwuid(getuid());
  postoffice->name = g_strdup (pw->pw_name);
  postoffice->dir = g_strdup (pw->pw_dir);


  /* check the MAIL environment variable for a spool directory */
  list = NULL;
  if (getenv("MAIL"))
    {
      mailbox = mailbox_new (postoffice, "INBOX", getenv ("MAIL"));
      list = g_list_append (list,  mailbox);
    }


  strcpy (filename, postoffice->dir);
  strcat (filename, "/mail");
  postoffice->maildir = g_strdup (filename);

  if (dp = opendir (postoffice->maildir))
    {
      while ((d = readdir(dp)) != NULL)
	{
	  sprintf(filename, "%s/%s", postoffice->maildir, d->d_name);

	  if (lstat (filename, &st) < 0)
	    {
	      balsa_error ("couldn't get info for file");
	      continue;
	    }

	  if (S_ISREG (st.st_mode))
	    {
	      mailbox = mailbox_new (postoffice, d->d_name, filename);
	      list = g_list_append (list, mailbox);
	    }
	}
    }

  postoffice->mailbox_list = list;

  return postoffice;
}
