#!/bin/bash
#
#   Routine to copy all of the necessary results.dat files
#   into the appropriate location so gen_grid_jobs has necessary
#   information
#
#  
#   First we need to get into the main directory
#
if [[  ! -d ./bin  ]]; then
    cd ../
    if [[ ! -d ./bin ]]; then
	echo "Error: store must be executed from the main, or bin directory"
	exit
    fi
fi
if [[ ! -d SubProcesses ]]; then
    echo "Error: SubProcesses directory not found"
    exit
fi
cd SubProcesses
if [[  "$1" == ""  ]]; then
    echo 'Enter you must specify a name to store files under. (eg restore_data TeV)'     
    exit
fi


if [[  "$1" == ""  ]]; then
    echo 'Enter you must specify a name to store files under. (eg restore_data TeV)'     
    exit
fi

if [[ -e $1_results.dat ]]; then
    cp  $1_results.dat results.dat  >& /dev/null
else
    cp  results.dat $1_results.dat  >& /dev/null
fi
    
for i in `cat subproc.mg` ; do
    cd $i
    echo $i
    rm -f ftn25 ftn26 >& /dev/null
    if [[ -e $1_results.dat ]]; then
	cp  $1_results.dat results.dat  >& /dev/null
    else
	cp  results.dat $1_results.dat  >& /dev/null
    fi
    cd ../
done

# check if we are on a Mac, otherwise assume Linux
if [[ "$OSTYPE" == "darwin"* ]]; then
    # no nproc on Mac, so use sysctl instead
    # use -S1024 because there is a limit on the length of the command
    xargs_opts="-P $(sysctl -n hw.ncpu) -S1024"
else
    xargs_opts="-P $(nproc --all)"
fi

find . -mindepth 2 -maxdepth 2 -type d -name 'G*' -print0 \
    | xargs --null ${xargs_opts} -I{} bash -c "
cd {}
for j in $1_results.dat ; do
    if [[ -e \$j ]] ; then
        cp \$j results.dat
    else
        cp results.dat \$j
    fi
done
for j in $1_ftn26.gz ; do
    if [[ -e \$j ]]; then
        rm -f ftn26 >& /dev/null
        rm -f $1_ftn26 >& /dev/null
        gunzip --keep \$j
        mv $1_ftn26 ftn26
    fi
done"
