set -e
if test -n "$BASH_VERSION"; then set -o posix; fi

# See https://www.gnu.org/prep/standards/html_node/Directory-Variables.html
prefix=/usr/local
exec_prefix='$(PREFIX)'
exec_suffix=
bindir='$(EXEC_PREFIX)/bin'
verbose=0


main() {
    parseArgs "$@"
    printMakefile > Makefile
}


printHelp() {
    echo ''
    echo "Example usage:   $0 --prefix /usr/local"
    echo ''
    echo 'Options:'
    echo '    --prefix "/usr/local"'
    echo '    --exec-prefix "$(PREFIX)"'
    echo '    --exec-suffix ""'
    echo '    --bindir "$(EXEC_PREFIX)/bin"'
    echo '    --verbose 0'
    echo ''
}


parseArgs() {
    # See: https://stackoverflow.com/a/14203146/4415884
    while test $# -gt 0 ; do
        case $1 in
            --help)        printHelp;       exit 1; ;;
            --prefix)      prefix="$2"      shift; shift; ;;
            --exec-prefix) exec_prefix="$2" shift; shift; ;;
            --exec-suffix) exec_suffix="$2" shift; shift; ;;
            --bindir)      bindir="$2"      shift; shift; ;;
            --verbose)     verbose="$2"     shift; shift; ;;
            *) echo "[ERROR] Unexpected argument: $1"; exit 1 ;;
        esac
    done
    if test "$verbose" != "0" -a "$verbose" != "1"; then
        echo "[ERROR] verbose expected to be 0 or 1. But is: $verbose";
        false;
    fi
}


printMakefile () {
    printf '\n'
    printf '%s\n' '# This file is generated by configure script. Manual changes may be lost'
    printf '%s\n' '# when calling configure again.'
    printf '\n'
    printf '%s\n' 'CC=gcc'
    printf '%s\n' 'TAR=tar'
    printf '%s\n' 'MKDIRS=mkdir -p'
    printf '%s\n' 'RIMRAF=rm -rf'
    printf '%s\n' 'COPYTO=cp -t'
    printf '%s\n' "PREFIX=$prefix"
    printf '%s\n' "EXEC_PREFIX=$exec_prefix"
    printf '%s\n' "EXEC_SUFFIX=$exec_suffix"
    printf '%s\n' "BINDIR=$bindir"
    printf '%s\n' "NDEBUG=1"

    # If PROJECT_VERSION set, use it.
    # If not, try generate via git describe.
    # If fails (eg git not avail), create pseudo version using date.
    printf '%s'   'PROJECT_VERSION=$(shell'
    printf '%s'   ' ret=$$(git describe --tags 2>/dev/null |sed -E "s;^v;;");'
    printf '%s'   ' if test -n "$$ret" -a -n "$$(git status --porcelain 2>/dev/null)"; then'
    printf '%s'       ' ret="$$ret+dirt";'
    printf '%s'   ' fi;'
    printf '%s'   ' if test -z "$$ret"; then ret=$$(date -u +0.0.0-%Y%m%d.%H%M%S); fi;'
    printf '%s\n' ' echo "$$ret")'

    printf '\n'
    printf '%s'   'CFLAGS= --std=c99'
    printf '%s'   ' -Wall -Wextra -Werror -fmax-errors=3'
    printf '%s'   ' -Wno-error=unused-function -Wno-error=unused-label'
    printf '%s'   ' -Wno-error=unused-variable -Wno-error=unused-parameter'
    printf '%s'   ' -Wno-error=unused-const-variable'
    printf '%s'   ' -Werror=implicit-fallthrough=1'
    printf '%s'   ' -Wno-error=unused-but-set-variable'
    printf '%s'   ' -Wno-unused-function -Wno-unused-parameter'
    printf '%s\n' ' -DPROJECT_VERSION=$(PROJECT_VERSION)'
    printf '%s\n' ''
    printf '%s\n' 'LDFLAGS= -Wl,--no-demangle,--fatal-warnings'
    printf '%s\n' ''
    printf '%s\n' 'INCDIRS= -Isrc/bulk_ln -Isrc/common'
    printf '%s\n' ''
    printf '%s\n' 'ifndef NDEBUG'
    printf '%s\n' '	CFLAGS := $(CFLAGS) -ggdb -O0 -g3'
    printf '%s\n' 'else'
    printf '%s\n' '	CFLAGS := $(CFLAGS) -ffunction-sections -fdata-sections -Os "-DNDEBUG=1"'
    printf '%s\n' '	LDFLAGS := $(LDFLAGS) -Wl,--gc-sections,--as-needed'
    printf '%s\n' 'endif'

    if test "$verbose" = "0"; then
        printf '\n'
        printf '%s\n' '.SILENT:';
    fi

    printf '\n'
    printf '%s\n' 'default: link dist'

    printf '\n'
    printf '%s\n' '.PHONY: clean'
    printf '%s\n' 'clean:'
    printf '%s\n' '	echo $(RIMRAF) build dist'
    printf '%s\n' '	$(RIMRAF) build dist'

    printf '\n'
    printf '%s\n' '.PHONY: link'
    printf '%s\n' 'link: build/bin/bulk-ln$(EXEC_SUFFIX)'

    printf '\n'
    printf '%s\n' 'build/obj/%.o: src/%.c'
    printf '%s\n' '	echo "  CC    $@"'
    printf '%s\n' '	$(MKDIRS) "$(shell T=$@; echo $${T%/*})"'
    printf '%s\n' '	$(CC) -c -o $@ $^ $(CFLAGS) $(INCDIRS)'

    printf '\n'
    printf '%s'   'build/bin/bulk-ln$(EXEC_SUFFIX):'
                  # dependencies
    printf '%s'   ' build/obj/bulk_ln/bulk_ln.o'
    printf '%s'   ' build/obj/bulk_ln/bulk_ln_main.o'
    printf '\n'   # commands
    printf '%s\n' '	echo "  LN    $@"'
    printf '%s\n' '	$(MKDIRS) "$(shell T=$@; echo $${T%/*})"'
    printf '%s\n' '	$(CC) -o $@ $(LDFLAGS) $^ $(LIBSDIR)'

    printf '\n'
    printf '%s\n' '.PHONY: dist'
    printf '%s\n' 'dist: link'
    printf '%s\n' '	echo "  Package"'
    printf '%s\n' '	$(RIMRAF) build/dist-* dist'
    printf '%s\n' '	$(MKDIRS) dist'
                  # Create Executable bundle.
    printf '%s\n' '	$(MKDIRS) build/dist-bin && $(COPYTO) build/dist-bin \'
    printf '%s\n' '		README*'
    printf '%s\n' '	$(MKDIRS) build/dist-bin/bin && $(COPYTO) build/dist-bin/bin \'
    printf '%s\n' '		build/bin/*'

    printf '%s\n' '	(cd build/dist-bin && find . -type f -not -name MD5SUM -exec md5sum -b {} +) > build/dist-bin/MD5SUM'

    printf '%s\n' '	(cd build/dist-bin && $(TAR) --owner=0 --group=0 -czf "../../dist/BulkLn-$(PROJECT_VERSION).tgz" *)'
    printf '%s\n' '	echo "" && echo "See '\''./dist/'\'' for result." && echo ""'
    printf '%s'   '	if test -n "$$(git status --porcelain 2>/dev/null)"; then'
    printf '%s'       ' echo "[WARN ] Worktree dirty!"; sleep 2;'
    printf '%s\n' ' fi'

    printf '\n'
    printf '%s\n' '.PHONY: install'
    printf '%s\n' 'install:'
    printf '%s\n' '	$(MKDIRS) "$(BINDIR)"'
    printf '%s\n' '	$(TAR) --strip-components=1 -C "$(BINDIR)" -xzf "$(shell ls dist/BulkLn-*.tgz)" -- bin'
}


main "$@"