#!/usr/bin/env python
'Parallel scons'
##   Copyright (C) 2010 University of Texas at Austin
##  
##   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

import sys, os, signal
import rsf.node

child = None

def handler(signum, frame):
    'signal handler for abortion [Ctrl-C]'
    global child
    sys.stderr.write('\n[Ctrl-C] Aborting...\n')
    if child:
        os.kill (signal.SIGINT,child)
    sys.exit(-1)

signal.signal(signal.SIGINT,handler) # handle interrupt

cpu = rsf.node.cpus()

cluster = os.environ.get('RSF_CLUSTER')
if not cluster:
    if os.environ.get('SLURM_NODELIST'):
        cluster=os.popen("slurm_nodelist2rsf_cluster").read()
if not cluster:
    cluster='localhost %d' % cpu

# We need one pscons thread for each remote task.  The number of
# remote tasks is the sum of the number of tasks on each of the
# nodes listed in the string "cluster"

cluster_list=cluster.split(" ")
threads=0
for indx_cluster in range(0,len(cluster_list),2):
    threads+=int(cluster_list[indx_cluster+1])

args = ' '.join(sys.argv[1:])
command = 'scons -j %d CLUSTER="%s" %s' % (threads,cluster,args)

sys.stderr.write(command+'\n')

# interruptable system command
child = os.fork()
if child:
    try:
        (pid,exit) = os.waitpid(child,0)
        sys.exit(exit)
    except OSError:
        sys.exit(0)
else:
    os.system(command)
    os._exit(0)

