/*
 * waitfor: small shell helper for waiting for files to appear.
 * Copyright (C) 2013 Scott Balneaves <sbalneav@ltsp.org>
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

/*
 * waitfor
 *
 * Simple program to check for a file either appearing, or disappeating, every
 * .2 seconds.  Optional timeout.  returns 1 if timeout, 0 if waited for event
 * happened.
 *
 * No timeout specified = wait indefinitely.
 */

int
main (int argc, char **argv)
{
  int exist = 1;
  int timeout = 0;
  const char *path;
  struct stat statbuf;
  int c;
  int st;
  int count;

  opterr = 0;

  while ((c = getopt (argc, argv, "nt:")) != -1)
    switch (c)
      {
      case 'n':
	exist = 0;
	break;
      case 't':
	timeout = atoi (optarg);
	break;
      default:
	exit (1);
      }

  path = argv[optind];

  timeout *= 5;

  for (count = 0; count <= timeout;)
    {
      st = stat (path, &statbuf);

      if (exist && st == 0)
	{
	  return 0;
	}

      if (!exist && st < 0)
	{
	  return 0;
	}

      usleep (200000);
      if (timeout)
	{
	  count++;
	}
    }

  return 1;
}
