#!/bin/bash

prog=${0##*/}

fail () {
    echo "$prog:" "$@" >&2
    exit 1
}

set -o nounset

Makefile=${1:-Makefile}
[[ -e $Makefile ]] || fail "$Makefile not found"
command -v make &>/dev/null  ||  fail "make not installed"

# List all the makefile targets (except 'list')
# https://stackoverflow.com/a/26339924
list () {
    make -pRrq -f "$Makefile" : 2>/dev/null \
        | awk -v RS= -F: \
            '/^# File/,/^# Finished Make data base/ {if ($1 !~ "^[#.]") {print $1}}' \
            | sort | grep -E -v -e '^[^[:alnum:]]' -e '^list$'
}
targets=$(list)
[[ -n $targets ]] || fail "Failed to get targets from $Makefile"
# ^-- TODO may not work if `list` returns leading/trailing spaces

targets_no_help=${targets/help/}

# https://stackoverflow.com/a/15394738
if [[ " $targets " =~ [[:space:]]help[[:space:]]  ]]; then
    make -f "$Makefile" help
    echo
fi

echo
echo "Pick a target:"
select tgt in $targets_no_help; do
    echo -n "Variables and flags? "
    read -r vars
    echo
    eval exec make -f "\"$Makefile\"" "$tgt" $vars
done


# vim:et:sw=4:sts=4:ts=8
