#!mkcmd
# $Id: util_tspace.m,v 1.3 2012/09/03 17:38:14 ksb Exp $
# Code to manage a /tmp/${SubSpace}XXXXXX mktemp space --ksb
# $Publish: ${install:-install} -c %f ${DESTDIR}/usr/local/lib/mkcmd/%[f_1]/%[f_-1]
from '<sysexits.h>'
from '<sys/stat.h>'

require 'util_ppm.m'

key "TSpaceInit" 1 init {
	"TSpaceInit" "(const char *)0"  "(const char *)0"
}
%ih
/* None */
%%
%@c
int
% %K<TSpaceInit>1ev(const char *pcSubSpace, const char *pcTmpPath)
{
	register unsigned short *puWas;
	register const char *pcScan;
	register char *pcMem;
	register int iLen, iX;
	auto time_t tNow;
	auto unsigned short ausSeed[3], ausOld[3];
	auto char acVamp[16];
	auto struct stat stDir;
	static const char acColon[] = ":";

	if ((const char *)0 == pcSubSpace) {
		if ((const char *)0 == (pcSubSpace = progname))
			pcSubSpace = "utsc";
	}
	if ((const char *)0 == pcTmpPath) {
		if ((char *)0 == (pcTmpPath = getenv("TMPDIR"))) {
			pcTmpPath = "/tmp:/var/tmp";
		}
	}
	if ((char *)0 != strchr(pcTmpPath, acColon[0])) {
		auto char *pcColon;
		register int iRet;

		iRet = EX_UNAVAILABLE;
		pcMem = strdup(pcTmpPath);
		for (pcScan = strtok_r(pcMem, acColon, &pcColon); (char *)0 != pcScan; pcScan = strtok_r((char *)0, acColon, &pcColon)) {
			if ('\000' == *pcScan)
				continue;
%				iRet = %K<TSpaceInit>1ev(pcSubSpace, pcScan);
			if (0 == iRet)
				break;
		}
		free((void *)pcMem);
		return iRet;
	}
	if (0 != stat(pcTmpPath, & stDir) || S_IFDIR != (S_IFMT & stDir.st_mode)) {
		return EX_NOINPUT;
	}
	iX = 0;
	for (pcScan = pcSubSpace; '\000' != *pcScan; ++pcScan) {
		if ('X' == *pcScan)
			++iX;
	}
	iLen = (strlen(pcTmpPath)|7)+1+((strlen(pcSubSpace)+8)|7)+1;
	if ((char *)0 == (pcMem = malloc(iLen))) {
		return EX_OSERR;
	}
	snprintf(pcMem, iLen, "%s/%s%s", pcTmpPath, pcSubSpace, iX < 6 ? "XXXXXX" : "");
	if ((char *)0 == mkdtemp(pcMem)) {
		free((void *)pcMem);
		return EX_NOINPUT;
	}
	return EX_OK;
}
/*	printf("%s: %s", progname, TSpaceInit("test", (char *)0));
 */
%%
