#!/usr/bin/env bash

# A wrapper for GHC that enables eventlogging when compiling packages with
# --make.


: ${GHC:?GHC must be set}
: ${EVENTLOG_DIR:?EVENTLOG_DIR must be set}

# Parse --make and unit-id out of args
#
# Example:
# -this-unit-id Cabal-3.0.2.0-b925bb4a908ac87dbee8e61089f84aad30e5791bc2f3e6ffef7bdbb944fda648
args=( "$@" )
i=0
unit_id=
make_mode=
while :
do
    k="${args[$i]}"
    v="${args[$i+1]}"
    if [[ $k == "--make" ]]
    then
        make_mode="$k"
    elif [[ -n $k && -n $v ]]
    then
        if [[ $k == "-this-unit-id" ]]
        then
            unit_id="$v"
            break
        fi
    else
        break
    fi
    (( i++ ))
done

# Continue with tracing, if applicable
if [[ -n $make_mode ]]
then
    log_args=${unit_id:+ +RTS -l -ol${EVENTLOG_DIR}/${unit_id}.eventlog -RTS}
fi
exec $GHC "$@"$log_args
