#!/bin/sh -e
#
# makemakefile - create Makefile for current project,
# based of presence of a build system configuration file.
#
# for example, if the current directory has a BUILD file
# makemakefile will copy `~/templates/Makefile.BUILD` to `./Makefile`.
#
# ---
# source: https://github.com/mikelward/scripts

DATAFILES_PATH=${DATAFILES_PATH:-${HOME}/.dotfiles/datafiles}

if [ -f "${HOME}/.rc" ]; then
  # shellcheck source=/dev/null
  . "${HOME}/.rc"
fi

cd "$1" >/dev/null

test -f .Makefile && exit 0

# hack: so we match BUILD and Makefile before angular.json and makefile.
LC_ALL=C

for f in "${DATAFILES_PATH}/templates/Makefile."*; do
  test -f "${f}" || break  # no templates
  if test -f "${f#"${DATAFILES_PATH}"/templates/Makefile.}"; then
    builddir="$(builddir)"
    sed -e 's#@BUILDDIR@#'"${builddir}"'#' "${f}" > .Makefile
    exit 0
  fi
done
