/*
 * send letter number 'n' to 'name'
 */

#include <stdio.h>
#include <pwd.h>
#include "mail.h"

extern char *Mailpgm, maildir[], sendto[256], *thissys;
extern FILE *malf;

send (n, name, level)
int n;
char *name;
{
  char file[50], *p, *px;
  struct passwd *pwd, *getpwnam ();

  if (level > 20)
  {
    fprintf (stdout, "unbounded forwarding\n");
    return (0);
  }
  if (strcmp (name, "-") == 0)
    return (1);
  for (p = name; *p != '!' && *p != '@' && *p != '\0'; p++)
    ;
#ifdef DEBUG
  printf ("DEBUG: *p=%c\n", *p);
  printf ("DEBUG: send: n=%d, name=%s\n", n, name);
  fflush (stdout);
#endif
  if (*p == '!' || *p == '@')
  {
    /* check to see if name is user@thissys or user@thissys.domain */
    px = strchr (name, '.');
    if (px != (char *) NULL)
      *px = NULL;
    if (strcmp (p + 1, thissys) == 0)
    {
      *p = NULL;
#ifdef DEBUG
      printf ("DEBUG: send: n=%d, name=%s\n", n, name);
      fflush (stdout);
#endif
      return (send (n, name, level + 1));
    }
    else
    {
      if (px != (char *) NULL)
	*px = '.';
#ifdef DEBUG
      printf ("DEBUG: sendrmt: n=%d, name=%s\n", n, name);
      fflush (stdout);
#endif
      return (sendrmt (n, name));
    }
  }
  /* cat (file, maildir, name); */
  if (areforwarding (file))
    return (send (n, sendto, level + 1));
  setpwent ();			       /* rewind password file -- dumb design */
  pwd = getpwnam (name);
  if (pwd == NULL)
  {
    fprintf (stdout, "%s: can't send to %s\n", Mailpgm, name);
    return (0);
  }
  cat (file, maildir, name);
  mailock (file);
  if (access (file, 0) < 0)
  {
    umask (0);
    close (creat (file, 0660));
    umask (MASK);

    /*
     * on some systems, only root can use chown() :(
     */
    setuid (0);
    chown (file, /* pwd->pw_uid */ realid, getegid ());
    setuid (realid);
  }
  malf = fopen (file, "a");
  if (malf == NULL)
  {
    fprintf (stdout, "%s: cannot append to %s\n", Mailpgm, file);
    unmailock ();
    return (0);
  }
  copylet (n, malf, ORDINARY, "");
  fclose (malf);
  unmailock ();
  return (1);
}
