/* $Id: ccsh.c,v 1.5 2000/05/17 07:08:23 dannys42 Exp $
 *
 * The CC Shell
 * Written by: Danny Sung  <dannys@mail.com>
 * Started date: March 18, 1998
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	char str[1024], *tmpfilename;
   char *runname;
   char *scriptname;
	int rtn;
	FILE *infile, *outfile;

   runname = argv[0];
   scriptname = argv[1];

   if( argc > 1 ) { 
      /* filename specified */
	   if( !(infile=fopen(scriptname, "r")) )
	   {
		   perror(runname);
         printf("  line: %d  file: %s\n", __LINE__, __FILE__);
		   exit(-EXIT_FAILURE);
	   }
   } else {
      /* run from stdin */
      infile = stdin;
   }

	if( (tmpfilename = tempnam(NULL, runname)) == NULL ) {
      perror(runname);
      printf("  line: %d  file: %s\n", __LINE__, __FILE__);
      exit(-EXIT_FAILURE);
   }
   
   sprintf(str, "%s.c", tmpfilename);
   if( !(outfile=fopen(str, "w+")) )
   {
      perror(runname);
      printf("  line: %d  file: %s\n", __LINE__, __FILE__);
      exit(-EXIT_FAILURE);
   }

   /* handle first line */
   if( fgets(str, 1024, infile) == NULL ) {
      unlink(tmpfilename);
      fclose(outfile);
      printf("Empty file.\n");
      exit(-EXIT_FAILURE);
   }

   if( strncmp(str, "#!", 2)==0 ) {
      /* we're being too smart for our own good here. lets just
       * comment this out for  now */
#if 0 
      /* Make sure we're running the right script */
      char *p;
      /* first remove newlines */
      if( (p = strchr(str, '\n')) )
         *p = 0;
      for(p=str+2; *p == ' ' && *p != 0; p++)
         ;
      if( strcmp(p, runname) != 0 ) {
         /* we're not running the correct script, so let's run it */
         fclose(infile);

         if( infile == stdin ) {
            /* This should probably do something usefull at some point.
             * Perhaps copy the stdin to a file, then execute it. */
            fprintf(stderr, "I'm sorry Dave, I can't do that.\n");
            exit(-1);
         }
         execv(p, argv);
      }
#endif
   } else {
      /* first line is does not indicate a shell */
      fputs(str, outfile);
   }

   /* write rest of lines */
   while( fgets(str, 1024, infile) ) {
      fputs(str, outfile);
   }
   fclose(outfile);
   fclose(infile);

   sprintf(str, "gcc %s.c -o %s", tmpfilename, tmpfilename);
   system(str);

   sprintf(str, "%s.c", tmpfilename);
   unlink(str);

   sprintf(str, "%s", tmpfilename);
   rtn = system(str);

   unlink(str);

   free(tmpfilename);
   return(rtn);
}

