/*
 * This file contains routines to deal with special types of files.
 * including compressed text and shell scripts.
 */


#include "gopherd.h"


/* Check to see if this file needs special treatment before heading
 * back to the client... We will check for:
 *	Compressed files	if so, zcat first
 *	Shellscript		if so, "do it"
 * Note: it would be somewhat non-portable to check of a binary
 *  (we'd need to check for so many different magic numbers; the
 *  shell script designation should be sufficient, since the script
 *  can call an executable anyway
 * Recognized elsewhere:
 *	.snd			needs special processing on client
 *	uuencoded		needs special processing on client
 * Other filetypes we could check for:
 *	GIF		->	Bring up GIF previewer
 *	Postscript	->	Bring up Postscript previewer
 */

static int ispipe;

FILE *
specialfile(fp, pathname)
  FILE *fp;
  char *pathname;
{
     FILE *pp;
     char buf[256], s[256];
     long i;
     
     ispipe = 0;
     
     /* Keep track of where we are */
     i = ftell(fp);
     rewind(fp);
     
     /* Grab the first three bytes, and rewind */
     if (fgets(s, 255, fp) == NULL)
	  return (FILE *)0;

     fseek(fp, i, 0);
     
     /* Compressed? */
     if (iscompressed(s)) {
	  if (dochroot)
	       sprintf(buf, "/bin/zcat \"%s\"\n", pathname);
	  else
	       sprintf(buf, "/usr/ucb/zcat \"%s/%s\"\n", Data_Dir, pathname);

	  if (! (pp = popen(buf, "r")))
	       return (FILE *)0;
	  ispipe = 1;
	  return pp;
     }

     /* Script? */
     if (isshellscript(s)) {
	  s[strlen(s)-1] = '\0';
	  if (dochroot)
	       sprintf(buf, "\"%s\" %s\n", pathname, (EXECargs == NULL) ? "" : EXECargs);
	  else
	       sprintf(buf, "\"%s/%s\" %s\n", Data_Dir, pathname, (EXECargs == NULL) ? "" : EXECargs);

	  if (DEBUG)
	       fprintf(stderr, "Executing %s", buf);

	  if (! (pp = popen(buf, "r")))
	       return (FILE *)0;
	  ispipe = 1;
	  
	  if (DEBUG)
	       fprintf(stderr, "Zcat popen is okay\n");
	  
	  return pp;
     }

     return (FILE *)0;
}


int
iscompressed(s)
  char *s;
{
     if ( (s[0] & 0xff ) == 0x1f && ( s[1] & 0xff ) == 0x9d)
	  return 1;
     else
	  return 0;
}

int
isshellscript(s)
  char *s;
{
     if (! strncmp(s, "#!/", 3))
	  return 1;
     else
	  return 0;
}


int
Specialclose(fp)
  FILE *fp;
{
     if (ispipe)
	  return(pclose(fp));
     else
	  return(fclose(fp));
}
