/*
 * $Id: rsleep.c,v 1.1 1994/02/14 13:04:31 casper Exp $
 *
 * Program to sleep a random number of seconds between
 * 0 and argv[1].
 *
 * Useful to keep clients from running the same cronjobs all
 * at once while still configuring them identically.
 *
 * Casper Dik
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/utsname.h>

#define DRAND_MAX 0x7fffffff

main(argc, argv)
int argc;
char **argv;
{
    long seconds, guess;
    char *p;
    struct hostent *hp;
    struct utsname name;
    long seed = getpid();

    if (argc != 2) {
	fprintf(stderr,"Usage: %s time-in-seconds\n", *argv);
	exit(1);
    }
    seconds = strtol(argv[1], &p, 0);
    if ((p && *p) || seconds < 0) {
	fprintf(stderr,"Usage: %s time-in-seconds\n", *argv);
	exit(1);
    }
    if (seconds == 0)
	exit(0);
    /* We don't want to use the time-of-day, we use the last 2 bytes
       of the host address, if we can find it */
    if (uname(&name) != -1 && (hp = gethostbyname(name.nodename))) {
	seed <<= 16;
	seed ^= (hp->h_addr_list[0][2] << 8) | (hp->h_addr_list[0][3]);
    }
    
    srand48(seed);
    guess = lrand48();
    /* scale 0 .. 2^31-1 to 0 .. seconds */
    guess = (double)guess * (double)seconds  / DRAND_MAX;
    if (seconds < guess) {
	fprintf(stderr,"Random time exceeds maximum time, DRAND_MAX error\n");
	guess = seconds / 2;
    }
    sleep(guess);
    exit(0);
}
