/*
 *  Login.app
 * 
 *  Copyright (c) 1997-2000 Per Liden
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
 *  USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
#include <stdarg.h>
#include <string.h>

#ifdef __FreeBSD__
extern char **environ;
#endif

void printError(const char *msg, ...) {
   va_list args;
   char    buf[512];
    
   va_start(args, msg);    
   vsprintf(buf, msg, args);
   strcat(buf,"\n");
   fflush(stdout);
   fputs("Login.app error: ",stderr);
   fputs(buf, stderr);
   fflush(stdout);
   fflush(stderr);
   va_end(args);
}

void* alloc(int size) {
   void *tmp;
    
   tmp = malloc(size);
   if (!tmp) {
      printError("out of memory, terminating");
      exit(0);
   } else {
      memset(tmp, 0, size);
   }

   return tmp;
}

char* getApplicationPath(const char* programPath) {
   char* path;
   int   i;

   path = strdup(programPath);

   for (i = strlen(path)-1; i >= 0; i--) {
      if(path[i] != '/') {
         path[i] = '\0';
      } else {
         break;
      }
   }
    
   if (path[0] == '\0') {
      free(path);
      path = strdup("./");
   }    

   return path;
}

char* stringCombine(const char* str1, const char* str2) {
   char* buffer;

   buffer = alloc(strlen(str1) + strlen(str2) + 1);
   strcpy(buffer, str1);
   strcat(buffer, str2);
   return buffer;
}

void executeScript(const char* path, const char* script) {
   char* command;
   int   pid;
   int   status;
   char* argv[2];

   command = stringCombine(path, script);

   if (command != 0) {
	
      pid = fork();
      switch (pid) {
      case -1:
         printError("could not execute %s (fork failed)", command);
         break;
	    
      case 0:
         argv[0] = (char*) script;
         argv[1] = 0;
         execve(command, argv, environ);
         printError("could not execute %s (execve failed)", command);
         exit(127);
         break;

      default:
         free(command);
         do {
            if (waitpid(pid, &status, 0) == -1) {
               if (errno != EINTR) {
                  break;
               }
            } else {
               break;
            }
         } while(1);
      }
   } else {
      printError("could not execute script (invalid script name)");
   }
}
