/*
   Routine to expand filename that contains shell variables
   Uses popen to fork/exec an echo to expand name if it contains shell
   metacharacters ($*{}[]?).
   Returns name if name does not contain "expandable" characters.
   Returns NULL if can't do echo or expanded name is not unique,
   and the modifier indicates this check should be done.
   Otherwise returns expanded name.
*/

#include <stdio.h>
#include "mail.h"

char *
expand(name, modifier)
char name[];
int   modifier;
{
   FILE *mypopen(), *fd;
   int mypclose();
   char *cp, command[512];
   extern char *strchr();

   if (!strpbrk(name, "$*{}[]\\?"))    /* return if no shell type chars */
      return(name);

   sprintf(command, "echo %s\n", name);

   if ((fd = mypopen(command, "r")) == NULL) {
      fprintf(stderr, "Can't echo\n");
      return(0);
   }

   fgets(command, sizeof(command), fd);   /* get expanded name */
   mypclose(fd);

   if ((cp = strchr(command, '\n')) != NULL)
      *cp = '\0';

   if (modifier & EX_UNIQ) {
      if (strchr(command, ' ')) {
         fprintf(stderr, "Ambiguous name\n");
         return(0);
      }
   }
   strcpy(name, command);
   return(name);
}
