#include <stdio.h>
#include <stdlib.h>

#include <fcntl.h>
#include <sys/ioctl.h>

#define BLKSETIDLE 4747
#define BLKGETIDLE 4748

void main(int argc, char *argv[])
{
  int fd;
  long timeout;

  if (argc < 2 || argc > 3)
  {
    fprintf(stderr, "usage: idle device [timeout]\n"
                   "  where timeout is the time until motor off in seconds\n"
                   "  a value of zero disables the idle function\n");
    exit(1);
  }

  if ((fd = open(argv[1], O_RDWR)) < 0)
  {
    perror(argv[1]);
    exit(1);
  }

  if (argc == 3)
  {
    timeout = atol(argv[2]);
    printf("Setting idle timeout of %s to %ld seconds\n", argv[1], timeout);
    if (ioctl(fd, BLKSETIDLE, &timeout) != 0)
    {
      perror(argv[1]);
      close(fd);
      exit(1);
    }
  }
  else
  {
    if (ioctl(fd, BLKGETIDLE, &timeout) != 0)
    {
      perror(argv[1]);
      close(fd);
      exit(1);
    }
    printf("Idle timeout for %s is %ld seconds\n", argv[1], timeout);
  }

  close(fd);

  exit(0);
}
