#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAS_SYSLOG
#include <syslog.h>
#endif
#include <fcntl.h>
#include <sysexits.h>
#include <sys/param.h>
#include <sys/stat.h>

#include "getopt.h"
#include "lutil.h"
#include "xutil.h"
#include "ftn.h"
#include "config.h"
#include "version.h"
#include "trap.h"


char *reqname(faddr *,char);
void mkdirs(char *name);


void usage(void)
{
  confusage("<node> filename\n");
}


int main(int argc, char *argv[])
{
  int c, i, rc;
  int reqind = 1;
  faddr *addr = NULL;
  char *reqfname = NULL;
  FILE *reqfile;
  struct flock fl;


#if defined(HAS_SYSLOG) && defined(CICOLOG)
  logfacility=CICOLOG;
#endif

  setmyname(argv[0]);
  catch(myname);

  while ((c = getopt(argc, argv, "hx:I:")) != -1)
  {
    if (confopt(c,optarg))
    {
      switch (c)
      {
       default:
	usage();
	exit(EX_USAGE);
      }
    }
  }

  if (readconfig())
  {
    fprintf(stderr, "Error getting configuration, aborting\n");
    exit(EX_DATAERR);
  }

  rc = 1;
  if (argv[optind] == NULL)
  {
    usage();
    rc = EX_USAGE;
  }
  else
  {
    if ((addr = parsefaddr(argv[optind++])) == NULL)
    {
      logerr("unrecognizable address \"%s\"", argv[optind]);
      rc = EX_USAGE;
    }
    else if (argv[optind] == NULL)
    {
      usage();
      rc = EX_USAGE;
    }
    else
    {
      reqind = optind;
    }
  }

  if (rc == 1)
  {
    /* set file umask */
    umask(066);

    reqfname = reqname(addr, 'o');
    mkdirs(reqfname);

    if ((reqfile = fopen(reqfname, "a")) == NULL)
    {
      logerr("$Unable to open request file %s", S(reqfname));
    }
    else
    {
      /* try to lock file for writing */
      fl.l_type = F_WRLCK;
      fl.l_whence = 0;
      fl.l_start = 0L;
      fl.l_len = 0L;
      if (fcntl(fileno(reqfile), F_SETLKW, &fl) < 0)
      {
	logerr("$Unable to lock request file %s", S(reqfname));
      }
      else
      {
	/* append entries to end of file */
	if (fseek(reqfile, 0L, SEEK_END))
	{
	  logerr("$Unable to seek in request file %s", S(reqfname));
	}
	else
	{
	  for (i = reqind; argv[i]; i++)
	  {
	    /* output with DOS newlines */
	    fprintf(reqfile, "%s\r\n", argv[i]);
	  }

	  if (!ferror(reqfile))
	  {
	    rc = 0;
	  }
	  else
	  {
	    logerr("$error writing to request file %s", S(reqfname));
	  }
	}
      }

      fclose(reqfile);
    }
  }

  return rc;
}
