/*
 * Copyright (C) 1998 Pierre Clerissi <clerissi@pratique.fr>
 */

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>

#include "../include/aftersteplib.h"

void
replaceEnvVar (char **path)
{
  char *varBegining = NULL;
  char *varEnding = NULL;
  char *varName = NULL;
  char *varValue = NULL;
  char *newPath = NULL;
  int varLength = 0;
  int pathLength = strlen (*path);
  if ((varBegining = strchr (*path, '$')) != NULL)
    {
      if ((varEnding = strchr (varBegining, '/')) != NULL)
	{
	  varLength = varEnding - varBegining;
	}
      else
	{
	  varLength = &(*path[pathLength - 1]) - varBegining;
	  varEnding = &(*path[pathLength - 1]);
	}

      strncpy (varName = (char *) safemalloc (varLength),
	       varBegining, varLength);
      varName[varLength] = '\0';

      if ((varValue = getenv (&varName[1])) != NULL)
	{
	  int newPathLength = 0;
	  newPathLength = pathLength - varLength + \
	    strlen (varValue);
	  newPath = (char *) safemalloc (newPathLength + 1);
	  memset (newPath, '\0', newPathLength + 1);
	  strncpy (newPath, *path, varBegining - *path);
	  strcat (newPath, varValue);
	  strcat (newPath, varEnding);
	  strcat (newPath, "\0");
	  free (*path);
	  *path = newPath;
	}
      free (varName);
    }
}
