#!/bin/sh
REPORT_TYPE="${REPORT_TYPE:-sast}"
REPORT="$CI_PROJECT_DIR/gl-$REPORT_TYPE-report.json"

if [ "$SECURE_LOG_LEVEL" = "debug" ]; then
    echo -e "\033[33;49m[DEBUG] ▶ Choosing the input analyzer report: '$REPORT'"
fi

OUTPUT="$CI_PROJECT_DIR/gl-report-post.json"
VET_STORE="$CI_PROJECT_DIR/vetstore"
VET_FEATURE_FLAG="sast_fp_reduction"
VET_TIMEOUT_SECS="${VET_TIMEOUT_SECS:=300}" #5m
TC_FEATURE_FLAG="vulnerability_finding_signatures"

echo "$GITLAB_FEATURES" | grep -q "$TC_FEATURE_FLAG"
tracking_enabled=$?

echo "$GITLAB_FEATURES" | grep -q "$VET_FEATURE_FLAG"
vet_enabled=$?

# Optionally configure base directory
SCRIPT_BASE_DIR="${SCRIPT_BASE_DIR:=/usr/local/bin}"

$SCRIPT_BASE_DIR/analyzer-binary "$@" || exit $?

[ $tracking_enabled -eq 0 ] && [ -f "$REPORT" ] && [ -f "$SCRIPT_BASE_DIR/analyzer-tracking" ] && {
    $SCRIPT_BASE_DIR/analyzer-tracking process \
        --report "$REPORT" \
        --output "$OUTPUT" \
        --repository "$CI_PROJECT_DIR" &&
        mv "$OUTPUT" "$REPORT"
}

VET_LANG_EXT="${VET_LANG_EXT:=.rb}"

# `run_with_timeout` runs the given command($2) for ($1) seconds.
# If the given command isn't complete within the ($1) seconds,
# it returns 1 otherwise 0.
#
# params:
# $1: Execution to timeout(in seconds)
# $2: Command to execute under timeout
run_with_timeout() {
    timeout_secs=$1
    cmd=$2

    # `timeout` command's trigger signal value depends on
    # the target docker environment -- Apline-based(Non-FIPS) or Fedora-based(FIPS).
    # Below check confirms if the env is running under busybox or not
    exe=$(
        exec 2>/dev/null
        readlink "/proc/$$/exe"
    )
    case "$exe" in
    # Alpine-based(Non FIPS) docker images uses BusyBox linux utils which
    # triggers SIGTERM(15) POSIX signal on timeout leading
    # to the final value 128+<SIGNAL_NUM> i.e, 143
    */busybox)
        signal_value=143
        ;;
    # Fedora-based(FIPS) images have GNU based linux utils that triggers
    # 124 status signal on timeout
    *)
        signal_value=124
        ;;
    esac

    timeout "$timeout_secs" sh -c "$cmd"

    # check if timeout occurred
    if [ $? -eq $signal_value ]; then
        return 1
    else
        return 0
    fi
}

[ $vet_enabled -eq 0 ] && [ -f "$REPORT" ] && [ -f "$SCRIPT_BASE_DIR/vet" ] && {

    vet_cmd="
        $SCRIPT_BASE_DIR/vet import \
                --src $CI_PROJECT_DIR \
                --store $VET_STORE \
                --file-ext $VET_LANG_EXT \
        && $SCRIPT_BASE_DIR/vet verify \
                --reportIn $REPORT \
                --reportOut $OUTPUT \
                --store $VET_STORE \
                --config $VET_CONFIGURATION_FILE \
        && mv $OUTPUT $REPORT
    "

    run_with_timeout "$VET_TIMEOUT_SECS" "$vet_cmd"

    [ $? -eq 1 ] && {
        echo -e "\033[33;49m[WARN] [VET] ▶ operation timed out, skipping false-positive reduction stage..."
    }
}

exit 0
