#!/usr/bin/env perl
# -*- perl -*-

#
# Author: Slaven Rezic
#
# Copyright (C) 1999,2003,2014 Slaven Rezic. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: slaven@rezic.de
# WWW:  http://bbbike.de
#

# Note: if MAKEFLAGS is empty, then this will result in an lone-standing
# dash. However, this does not seem to hurt GNU make.

print ".CURDIR?=	\${CURDIR}\n";
while(<STDIN>) {
    s/^\.if\s+defined\(([^\)]+)\)/ifdef $1/;
    s/^\.ifdef ([^\)]+)/ifdef $1/;
    s/^\.ifndef ([^\)]+)/ifndef $1/;
    s/^\.if\s+exists\((.+)\)/ifeq (\$(shell test -e $1 && echo 1 || echo 0),1)/;
    s/^\.if(.+)eq(.+)/ifeq $1 $2/;
    s/^\.if(.+)ne(.+)/ifneq $1 $2/;
    s/^\.else(\s+)/else$1/;
    s/^\.endif(\s+)/endif$1/;
    s/^\.error (.+)/\$(error $1)/;
    s/^\.include "Makefile(.+)"/include GNUmakefile$1/; # Hack --- all Makefiles should be translated into GNUmakefiles
    s/^\.include "(.+)"/include $1/;
    s/^\.endfor//;#XXX
    s/\$\{\.?MAKEFLAGS\}/-\${MAKEFLAGS}/g;
    s/\$\(\.?MAKEFLAGS\)/-\${MAKEFLAGS}/g;
    s/\$>/\$^/g;
    s[\$\{(.*):M/(.*)/(.*)/}][\$($1:$2=$3)]g;
    s[\$\{(.*):C/(.*)(?<!\\)/(.*)(?<!\\)/(g)?}][]g;
    s[\!=(\s*)(.*)][=$1\$(shell $2)]g;
    if (/^\.for\s+(\S+)\s+in\s+(\S+)/) { # XXX not implementable in GNU make?
	my($loopvar, $subst) = @_;
	my $for_body = "";
	while(<STDIN>) {
	    last if /^\.endfor/;
	    $for_body .= $_;
	}
#	print $for_body;
	next;
    }
    print;
}

__END__
