/*****************************************************************************\
*                                                                             *
*  Name   : output_capture                                                    *
*  Author : Chris Koeritz                                                     *
*                                                                             *
*  Purpose:                                                                   *
*                                                                             *
*    This program runs a command and sends the output to the first parameter. *
*                                                                             *
*******************************************************************************
* Copyright (c) 1991-$now By Author.  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 is online at:      *
*     http://www.fsf.org/copyleft/gpl.html                                    *
* Please send any updates to: fred@gruntose.com                               *
\*****************************************************************************/

#include <opsystem/console_logger.h>
#include <opsystem/ini_config.h>
#include <opsystem/startup_code.h>

#include <fcntl.h>
#ifdef __WIN32__
  #include <io.h>
#endif
#include <stdio.h>

HOOPLE_STARTUP_CODE;

#define LOG(to_print) program_wide_logger().log(to_print)

int main(int argc, char *argv[])
{
  SET_DEFAULT_CONSOLE_LOGGER;
  if (argc < 3) {
    LOG("The first parameter should be the output file and the second through Nth");
    LOG("parameters should be the command to execute.");
    return 37;  // error.
  }

  istring output_file = argv[1];

  // redirect standard output to our file.
  close(1);
  open(output_file.s(), O_WRONLY|O_CREAT|O_TRUNC, 0);

  istring program = argv[2];
  istring args;

  for (int i = 3; i < argc; i++) {
    args += istring("\"") + argv[i] + "\" ";
  }

  u_int kid;
  if (portable::launch_process(program, args, portable::AWAIT_APP_EXIT, kid)) {
    // failed.
    LOG(istring("failed to execute the command: ") + program);
    return 20;
  }

  return 0;
}

