#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include "errors.h"
#include "office.h"
#include "sendz.h"

enum {
  buflen = 1024
};

static char *zbot_opts = "z";

static void usage(const char *progname);
/* requires: progname is a valid C string
 * effects: Writes a usage message to stderr.
 */

#define S_PER_HR 3600

#define HOUR S_PER_HR

#if 0
int snprintf(char *, int, const char *, ...);

int snprintf(char *s, int slen, const char *fmt, ...)
{
  va_list ap;
  int     i;

  va_start(ap, fmt);
  i = vsprintf(s, fmt, ap);
  va_end(ap);

  return i;
}
#endif

int main(int argc, char **argv)
{
  int  ch, delay, zephyr_test = 0;

  srand48(time(NULL));

  while ((ch = getopt(argc, argv, zbot_opts)) != EOF) {
    switch(ch) {
    case 'z':
      zephyr_test = 1;
      break;

    case '?':
      usage(argv[0]);
      exit(0);
      
    default:
      fprintf(stderr, "%s: INTERNAL ERROR", argv[0]);
      fprintf(stderr, "%s: unexpected option character \'%c\' from getopt()\n", 
	      argv[0], ch);
      abort();
    }
  }

  if (zephyr_test) {
    sendz_send_zephyrs();
    exit(0);
  }

  office_read_head_list("office_heads.txt");

  /* This loop:
   *   wait until the office can be cleaned.
   *   announce an office cleaning.
   *   wait until the minimum inter-cleaning time is elapsed.
   *   wait until the hour randomly selected for cleaning.
   *   "desync" ourselves
   */
  while (1) {
    delay = (int) (drand48() * HOUR);
    printf("%s %s: desyncing by %d seconds\n", now_string(),
	    argv[0], delay);
    fflush(stdout);

    sendz_send_zephyr_debugging("Desyncing by %d seconds", delay);

    sleep(delay);

    while (!office_try_clean_now()) {
      sleep(HOUR);
    }

    office_now_cleaned();

    printf("%s %s: Office cleaning announced\n",
	    now_string(), argv[0]);
    fflush(stdout);

    sendz_send_zephyr_debugging("Office cleaning announced");
    
    while(!office_needs_cleaning()) {
      sleep(HOUR);
    }

    while (!office_should_clean()) {
      sleep(HOUR);
    }
  }

  return 0;
}

static void usage(const char *progname)
{
  fprintf(stderr, "%s: usage:\n", progname);
  fprintf(stderr, "  %s [-z]\n", progname);
}





