/* printenv: prints value of environment, or of variable -*-
/* mly840324 */

/* "printenv" prints ENVVARNAME=ENVVARVALUE<newline> for all env vars.
    Returns 0.
   "printenv ENVVARNAME" prints ENVVARVALUE<newline>
    Returns 0 if ENVVARNAME defined in environ, else 1
   returns 2 if given losing args.
*/

#include <stdio.h>

char *progname;

main (argc, argv, envp)
     int argc;
     char **argv;
     char **envp;
{
  register char **env;
  register char *q, *p;
  extern char *index ();

  progname = argv[0];
  if (argc > 2)
    barf ("too many arguments (%d)\n\
\tExpected either no args,\n\
\tor an argument of a single environment variable name.",
	  argc);

  if (argc > 1 && index (argv[1], '='))
    barf ("bad environment variable name \"%s\"\n\
\tEnvironment variables may not contain the \"=\" character.",
	  argv[1]);

  for (env = envp; *env; env++)
    {
      if (argc == 1)
	printf("%s\n", *env);
      else
	{
	  p = *env; q = argv[1];
	  while (*p && *q && *p++ == *q++)
	  if ((*p == '=') && (*q == 0))
	    {
	      printf ("%s\n",++p);
	      exit (0);
	    }
	}
    }
  exit ((argc == 1) ? 0 : 1);
}

/* print error message and die with exit code 2 */
barf (string, arg)
     char *string, *arg;
{
  fprintf (stderr, "%s: ", progname);
  fprintf (stderr, string, arg);
  fprintf (stderr, "\n");
  exit (2);
}
