#!/bin/bash
# Ilkay Alakay <ilkay@astronix.org>. Licensed under The Unlicense

DIR="$(pwd)"
IMAKEFILE="$DIR/IMakefile"
TARGET="${1:-compile}"

if [[ ! -f "$IMAKEFILE" ]]; then
    echo "imake: IMakefile not found in $DIR" >&2
    exit 1
fi

if ! grep -qE "^${TARGET}:" "$IMAKEFILE"; then
    echo "imake: *** no rule to make target '$TARGET'. stop." >&2
    exit 1
fi

in_target=0

while IFS= read -r line || [[ -n "$line" ]]; do
    [[ "$line" =~ ^[[:space:]]*$ ]] && continue
    [[ "$line" =~ ^[[:space:]]*# ]] && continue

    if [[ "$line" =~ ^([a-zA-Z0-9_-]+):[[:space:]]*$ ]]; then
        current_target="${BASH_REMATCH[1]}"
        if [[ "$current_target" == "$TARGET" ]]; then
            in_target=1
        else
            in_target=0
        fi
        continue
    fi

    if [[ $in_target -eq 1 ]]; then
        [[ "$line" =~ ^[[:space:]]*(.*)$ ]]
        cmd_print="${BASH_REMATCH[1]}"

        printf '%s:\n' "$cmd_print"

        output=$(bash -c "$line" 2>&1)
        status=$?

        if [[ -n "$output" ]]; then
            while IFS= read -r output_line || [[ -n "$output_line" ]]; do
                printf '                %s\n' "$output_line"
            done <<< "$output"
        else
            printf '                \n'
        fi

        if [[ $status -ne 0 ]]; then
            printf '                command failed with exit code %d\n' "$status"
            exit "$status"
        fi
    fi
done < "$IMAKEFILE"
