/*	SCCS Id: @(#)unixunix.c	3.4	1994/11/07	*/
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/* NetHack may be freely redistributed.  See license for details. */

/* This file collects some Unix dependencies */

#include "hack.h"	/* mainly for index() which depends on BSD */

#include <errno.h>
#include <sys/stat.h>
#include <signal.h>
#include <stdio.h>

void
getlock() /* Stolen from mac version, then beaten into submission */
{
	FILE *f;
	int pid = getpid(); /* Process ID */
	
	set_levelfile_name(lock,0);

	f = fopen(lock,"w");
	if (f == NULL)
	{
		raw_printf("Could not lock the game %s.", lock);
		panic("Doh!");
	}
	fputc(pid & 255,f);
	fputc((pid >> 8) & 255,f); 
	fputc((pid >> 16) & 255,f);
	fputc((pid >> 24) & 255,f);
	fclose(f); 
}

void
regularize(s)	/* normalize file name - we don't like .'s, /'s, spaces */
register char *s;
{
	register char *lp;

	while((lp=index(s, '.')) || (lp=index(s, '/')) || (lp=index(s,' ')))
		*lp = '_';
#ifdef RUNTIME_SHORT_FILENAMES
	/* avoid problems with 10 character file name limit */
# ifdef COMPRESS
	/* leave room for .e from error and .Z from compress appended to
	 * save files */
	{
#  ifdef COMPRESS_EXTENSION
	    int i = 8 - strlen(COMPRESS_EXTENSION); /* Are these lengths right? I've just shortened them all by 4... (14->10) */
#  else
	    int i = 6;		/* should never happen... */
#  endif
	    if(strlen(s) > i)
		s[i] = '\0';
	}
# else
	if(strlen(s) > 7)
		/* leave room for .nn appended to level files */
		s[7] = '\0';
# endif
#endif
}

#ifdef SHELL
int
dosh()
{
	register char *str;
	if(child(0)) {
		if((str = getenv("SHELL")) != (char*)0)
			(void) execl(str, str, (char *)0);
		else
			(void) execl("/bin/sh", "sh", (char *)0);
		raw_print("sh: cannot execute.");
		exit(EXIT_FAILURE);
	}
	return 0;
}
#endif /* SHELL */

#if defined(SHELL) || defined(DEF_PAGER) || defined(DEF_MAILREADER)
int
child(wt)
int wt;
{
	register int f;
	suspend_nhwindows((char *)0);	/* also calls end_screen() */
	if((f = fork()) == 0){		/* child */
		(void) setgid(getgid());
		(void) setuid(getuid());
#ifdef CHDIR
		(void) chdir(getenv("HOME"));
#endif
		return(1);
	}
	if(f == -1) {	/* cannot fork */
		pline("Fork failed.  Try again.");
		return(0);
	}
	/* fork succeeded; wait for child to exit */
	(void) signal(SIGINT,SIG_IGN);
	(void) signal(SIGQUIT,SIG_IGN);
	(void) wait( (int *) 0);
	(void) signal(SIGINT, (SIG_RET_TYPE) done1);
#ifdef WIZARD
	if(wizard) (void) signal(SIGQUIT,SIG_DFL);
#endif
	if(wt) {
		raw_print("");
		wait_synch();
	}
	resume_nhwindows();
	return(0);
}
#endif

#ifdef GETRES_SUPPORT

/* Hard-wire id's to 1 */

int
(getresuid)(ruid, euid, suid)
uid_t *ruid, *euid, *suid;
{
    return 1;
}

uid_t
(getuid)()
{
    return 1;
}

uid_t
(geteuid)()
{
    return 1;
}

int
(getresgid)(rgid, egid, sgid)
gid_t *rgid, *egid, *sgid;
{
    return 1;
}

gid_t
(getgid)()
{
    return 1;
}

gid_t
(getegid)()
{
    return 1;
}

#endif	/* GETRES_SUPPORT */
