#!/bin/sh
# Copyright (c) 2016-2018, Yannick Cote <yanick@divyan.org>. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file.

# This small script calls mconfig the same way it was first as recorded in
# the previously generated ./Makefile.

set -e

printonly="n"

if [ ! -f "./Makefile" ]; then
	echo "could not find \`Makefile'"
	exit 2
fi

# check line options
while getopts p name; do
 case $name in
  p) printonly="y";;
  ?) echo "usage: ${0##*/} [-p]"
     echo "  -p : print mconfig command only, don't run"
     exit 2;;
 esac
done

lastcmd=`cat ./Makefile | awk \
	'BEGIN { \
		FS="# configured: "; \
		for (i = 0; i < 4 && getline < "./Makefile" > 0; i++) { \
			if ($2 != "") \
				printf("%s", $2) \
			} \
		}'`
if [ -z "$lastcmd" ]; then
	echo "no mconfig line: is Makefile generated by mconfig?"
	exit 2
fi
if [ "$printonly" = "y" ]; then
	echo $lastcmd
else
	$lastcmd
fi
