#!/usr/bin/env python
# startprocess - runs a process in background with redirection of output/error
#
# Author: David Mastronarde
#
# $Id: startprocess,v d0699dca576c 2024/04/29 14:41:24 mast $

progname = 'startprocess'
prefix = 'ERROR: ' + progname + ' - '

# load System Libraries
import sys, os

#
# Setup runtime environment
if os.getenv('IMOD_DIR') != None:
   IMOD_DIR = os.environ['IMOD_DIR']
   if sys.platform == 'cygwin' and sys.version_info[0] > 2:
      IMOD_DIR = IMOD_DIR.replace('\\', '/')
      if IMOD_DIR[1] == ':' and IMOD_DIR[2] == '/':
         IMOD_DIR = '/cygdrive/' + IMOD_DIR[0].lower() + IMOD_DIR[2:]
   sys.path.insert(0, os.path.join(IMOD_DIR, 'pylib'))
   from imodpy import *
   addIMODbinIgnoreSIGHUP()
else:
   sys.stdout.write(prefix + " IMOD_DIR is not defined!\n")
   sys.exit(1)

#
# load IMOD Libraries
from pip import exitError, setExitPrefix

setExitPrefix(prefix)

if len(sys.argv) < 2:
   prnstr("Usage: " + progname + \
             """ [-o outfile] [-e errfile] [-a] [-d dir] command arguments...
   Runs a process in the background with optional redirection of the output
      outfile is a file for standard output
      errfile is a file for standard error, or 'None' for no redirection
      -a option will make it append to these files if they exist
      dir is a working directory to set before running the command; errfile
          and outfile are relative to this directory
   The default is no redirection of standard output, and redirection of
      standard error into standard output (use '-e None' to override)""")
   sys.exit(0)

argind = 1
outfile = None
errfile = 'stdout'
workdir = None
doAppend = False
while argind < len(sys.argv) - 1:
   if sys.argv[argind] == '-o':
      outfile = sys.argv[argind + 1]
      argind += 2
      continue
   elif sys.argv[argind] == '-e':
      errfile = sys.argv[argind + 1]
      argind += 2
      if errfile == 'None':
         errfile = None
      continue
   if sys.argv[argind] == '-d':
      workdir = sys.argv[argind + 1]
      argind += 2
      continue
   if sys.argv[argind] == '-a':
      doAppend = True
      argind += 1
      continue
   else:
      break
   
if argind >= len(sys.argv):
   exitError("No command was included")

if workdir:
   try:
      os.chdir(workdir)
   except:
      exitError('Changing working directory to ' + workdir)
   
bkgdProcess(sys.argv[argind:], outfile, errfile, append = doAppend)
sys.exit(0)
