#!/bin/bash

set -euo pipefail

MAKE=$1 # make tool
MAKEFILE=$2 # root makefile
ROOT_TARGETS_ONLY=${3:-false} # print root Makefile targets only

# Get number of available colors
COLORS_NUM=$(tput colors)
# Then check if it's a terminal and we have enough colors
if [ -t 1 ] && [ -n "$COLORS_NUM" ] && [ "$COLORS_NUM" -ge 4 ]; then
    RESET="$(tput sgr0)"
    RED="$(tput setaf 1)"
    GREEN="$(tput setaf 2)"
    BLUE="$(tput setaf 4)"
    
else
    RESET=
    RED=
    GREEN=
fi

# See https://stackoverflow.com/a/26339924 for different approaches.

# Here ":" is a non-existing target, -q doesn't run anything.
MAKE_DB=$(LC_ALL=C $MAKE \
    --print-data-base \
    --no-builtin-rules \
    --no-builtin-variables \
    -q \
    --makefile="$MAKEFILE" \
    : 2>/dev/null || true)


echo "Detailed platform usage description: ${BLUE}https://git.mws-team.ru/mws/devp/platform-go/-/blob/master/README.md${RESET}"

echo "${RED}Makefile targets:${RESET}"

# -v RS= splits MAKE_DB into "paragraphs" separated with "\n\n+"
# -F: splits into ":"-separated fields, we use only the first field $1
# -v FILTER="$ROOT_TARGETS_ONLY" if 'true' - filters out just root Makefile targets
# /^[A-Za-z]/ filters out "# Not a target:" and internal targets like .DEFAULT
# match+substr extracts help string which is a command that is a comment - "@# ...".
# (Because MAKE_DB doesn't preserve Makefile comments)

echo "$MAKE_DB" | awk \
    -v RS= \
    -F: \
    -v GREEN=$GREEN -v RESET=$RESET \
    -v FILTER="$ROOT_TARGETS_ONLY" \
    '/^[A-Za-z]/ {
        if (FILTER == "true" && $0 !~ /from `Makefile/) next;
        match($0, /@#[^\n]*/);
        HELP_STR=substr($0, RSTART+1, RLENGTH-1);
        printf("%s:%s%s%s\n", $1, GREEN, HELP_STR, RESET);
    }' | sort | column -s ':' -t
