/*
 * nqsd/all-systems/nqs_tmpdir.c
 * Working directory support, based on original implementation by
 * Dave Safford (saff@tamu.edu)
 * 
 * Modularised for GNQS 3.50.0 by Stuart Herbert
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <libnqs/defines.h>

#include <libsal/license.h>
#include <libsal/proto.h>
#include <libsal/defines.h>

#include <SETUP/autoconf.h>
#include <nqsdaemon/features.h>

#include <stdlib.h>

#if ADD_NQS_TMPDIR
static void nqs_MakeTmpdir(struct rawreq *, char *);

void nqs_CreateTmpdir
(
 struct rawreq *pstRawreq, 
 struct passwd *pstPasswd,
 char          *szEnvironment,
 char	       **szEnvp,
 int	        iEnvpcount,
 int	       *piEnvpsize
)
{
  char szTmpdir[MAX_PATHNAME];
  char szMkdir [MAX_PATHNAME + 1024];
  char *pChar;
  
  /* get the name of the temporary directory */
  nqs_MakeTmpdir(pstRawreq, szTmpdir);
  
  sprintf (szMkdir,"%s -p -m 755 %s", MKDIR, szTmpdir);
  system(szMkdir);
  if (chown(szTmpdir, pstPasswd->pw_uid, pstPasswd->pw_gid) ==-1)
  {
    sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_WARNING, "Unable to change permissions on TMPDIR %s\n", szMkdir);
    sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_DEBUGMEDIUM, "Userid : %d\nGroupid : %d\n", pstPasswd->pw_uid, pstPasswd->pw_gid);
  }
  
  pChar = szEnvironment + *piEnvpsize;
  szEnvp[iEnvpcount++] = pChar;
  *piEnvpsize += sprintf(pChar, "TMPDIR=%s", szTmpdir) + 1;
  szEnvp[iEnvpcount] = (char *) 0;
}

void nqs_RemoveTmpdir(struct rawreq *pstRawreq)
{
  char szTmpdir[MAX_PATHNAME];
  char szRmCmd [MAX_PATHNAME + 1024];
  
  nqs_MakeTmpdir(pstRawreq, szTmpdir);
  sprintf(szRmCmd, "rm -rf %s", szTmpdir);
  system(szRmCmd);
}

static void nqs_MakeTmpdir(struct rawreq *pstRawreq, char *szTmpdir)
{
  char *szHostname;
  
  szHostname = nmap_get_nam(pstRawreq->orig_mid);
  sprintf(szTmpdir, "%s/%s/%ld.%s", NQS_TMPDIR_HOME, pstRawreq->quename,
	  pstRawreq->orig_seqno, szHostname);
}

#endif /* ADD_NQS_TMPDIR */
