#!/bin/bash

function handler()
{
    kill -s SIGINT $CFPID
    kill -s SIGINT $APID
    kill -s SIGINT $BPID
    kill -9 $GPID
}

cd ./crazyflie_groundstation

if [ $# -gt 0 ]
then
    echo "custom radio"
    ./crazyflieGroundStation $1 &
else
    echo "default radio"
    ./crazyflieGroundStation &
fi
CFPID=$!

echo "Waiting for crazyflie groundstation to be created..."
cf_gs=crazyflie_groundstation.socket
while [ ! -S "$cf_gs"  ]
do
    sleep 1
done

cd ../groundStation/adapters/crazyflie
sleep 1
./bin/cf_adapter &
APID=$!

sleep 1
cd ../..
./BackEnd &
BPID=$!

# if [ ! ps -p $CFPID -gt /dev/null || ! ps -p $APID -gt /dev/null || ! ps -p $BPID -gt /dev/null ]
# then
#     echo "enter if"
#     if [ ps -p $CFPID -gt /dev/null ]
#     then
#         kill -s SIGINT $CFPID
#     fi

#     if [ ps -p $APID -gt /dev/null ]
#     then
#         kill -s SIGINT $APID
#     fi

#     if [ ps -p $BPID -gt /dev/null ]
#     then
#         kill -s SIGINT $CFPID
#     fi
#     exit
# fi

if [ "$2" = "nogui" ]
then
    x-terminal-emulator .
    GPID=$!
else
    ./GroundStation &
    GPID=$!
fi

trap handler INT

wait