#!/bin/bash

# * "a || b" disables "-e" and is not reactivatable
# * forking removes traps
# * Signals are not handled while "sleep"

set -e
set -u

error=0
pidArray=()

mainTrap()
{
    echo "### Main: something happened"
    # return 0
}

failTrap()
{
    sta=$?
    if [ "$$" != "$BASHPID" ]; then
       echo $sta > return_$BASHPID
       error=1
	kill -s SIGINT $$
       #echo $
       #echo "TRAP $sta; $$; $BASHPID"
    else
	#echo "MAIN"
	echo "Trap in main process? I don't think so!"
	exit 22
    fi
}

fail()
{
    # set -e
    # trap failTrap EXIT
    echo A2.1
    gcc
    # return 22
    echo A2.2
    return 22
}

fail2()
{
    # set -e
    # trap failTrap EXIT
    echo A3.1
    sleep 5
    exit 22
    # return 22
    echo A3.2
    return 22
}

semiSucceed()
{
    return -5000
}

succeed()
{
    # set -e
    echo A2.1 S
    semiSucceed
    echo A2.2 S
    return 0
}

runLogged()
{
    trap failTrap EXIT
    $@ &> $BASHPID.log
}

sta=0

echo "Start: $$; $BASHPID"

trap -- mainTrap SIGINT

echo "A"
# fail || sta=1
runLogged fail &
subPid=$!
pidArray+=( $subPid )
echo "Forked: $subPid"

runLogged succeed &
subPid=$!
pidArray+=( $subPid )
echo "Forked: $subPid"

runLogged fail2 &
subPid=$!
pidArray+=( $subPid )
echo "Forked: $subPid"

echo "----------------------------------------"
wait

for pid in ${pidArray[*]}; do
    echo
    echo
    echo "CHECK $pid"
    ret=$(cat return_$pid)
    if [ "$ret" != "0" ]; then
	echo "$pid: Error $ret"
	echo "log:"
	cat $pid.log
    else
	echo "$pid: OK"
	echo "log:"
	cat $pid.log
    fi
done

echo

echo "B: $sta / $error"

echo "Fin."

sleep 0.5
echo "(B: $sta / $error)"


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