/*
 * play: shall we play a game?
 */
static const char rcsid[] = "Mastodon $Id: s.play.c 1.3 99/05/04 19:33:05-00:00 orc $";

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>


#define GAMES	"/usr/games/"
#define LOCK	"locked"


main(int argc, char **argv)
{
    char bfr[1024];
    int x;
    int size;

    if (argc < 2) {
	fprintf(stderr, "usage: play game [args]\n");
	exit(1);
    }

    /* check to see if the games directory is locked.  If it is,
     * spit out the contents of the lockfile and exit
     */
    if ((x = open(GAMES LOCK, O_RDONLY)) != -1) {
	while ((size = read(x, bfr, sizeof bfr)) > 0)
	    write(1, bfr, size);
	close(x);
	exit(1);
    }

    /* no lockfile.  Is it because it doesn't exist or because
     * we're not setuid and it's not letting us in?
     */
    if (errno != ENOENT) {
	perror(GAMES LOCK);
	exit(1);
    }


    /* the lockfile doesn't exist, so we can party, we hope.
     */

    if (chdir(GAMES) != 0) {
	perror(GAMES);
	exit(1);
    }

    if (strcasecmp(argv[1], "list") == 0) {
	struct dirent *de;
	DIR *dp;
	int ct;
	struct stat st;

	if (dp = opendir(".")) {
	    for ( (ct=0),(de = readdir(dp)); de; de = readdir(dp) )
		if (stat(de->d_name, &st) == 0 && S_ISREG(st.st_mode)
					       && (st.st_mode & S_IXUSR)) {
		    ++ct;
		    printf((ct % 5) ? "%-16s" : "%s\n", de->d_name);
		}
	    if (ct % 5)
		putchar('\n');
	    closedir(dp);
	}
	else
	    perror(GAMES);
	exit(0);
    }


    /* first change our permissions back to ourself
     */
    setgid(getegid());
    setuid(geteuid());

    argc--, argv++;
    snprintf(bfr, sizeof bfr, GAMES "%s", argv[0]);

    execv(bfr, argv);
    perror(argv[0]);
    exit(1);
} /* play */
