#!/bin/bash

set -e
set -u

mkdir -p workspace/log
WORKSPACE=$PWD/workspace
opwd=$PWD

trapFunction()
{
   local sta=$?
   cd $opwd
   # echo "Return code: $sta"
   echo $sta > $WORKSPACE/log/return_$BASHPID.log
   if [ "$sta" != "0" ]; then
      echo "Return code: $sta in process $BASHPID"
      echo "PWD: $PWD, cmd=$0"
      kill -s SIGINT $$
      
        # echo "Sending signal to parent"
   fi
   wait
   # This will wait forever?
   # waitRemainingSilent $BASHPID
}

function trapParent()
{
   sta=1
   {
      flock -s 200
      # echo -e "\nSomething happened\n"
      let childErrors+=1
    } 200>$WORKSPACE/log/trap.lock
}


function fail()
{
    sleep 0.5
    echo "FAIL"
    return 10
    # exit 1
}

function runLoged()
{
    trap trapFunction EXIT
    # echo "Started $BASHPID; Args: $@; PWD: $PWD"
    # echo "PWD: $PWD"
    echo "PWD: $PWD" >> $WORKSPACE/log/cmd_$BASHPID.log
    echo "CMD: $@" >> $WORKSPACE/log/cmd_$BASHPID.log
    $@ &> $WORKSPACE/log/log_$BASHPID.log
    # trap is not always called on exit
    echo $? > $WORKSPACE/log/return_ok_$BASHPID.log
    waitRemainingSilent $BASHPID
    echo "Logged ended"
}


runLoged fail
wait
echo "Fin."


#---fin------------------------------------------------------------------------
