#!/usr/bin/perl
#
# make gnut and install binary
#
# 20010517 It now works if invoked as "../mk" from within the src subdirectory

$| = 1;

$cdir = `pwd`; chop $cdir;
if ($cdir =~ m|/src$|) {
  chdir("..");
}

close STDERR;
open(STDERR, ">&STDOUT");

$arg = shift;

$fb = 0;

if ($arg eq "foolproof") {
  $fb = 1;
}
if (!(-e "Makefile")) {
  $fb = 1;
}

if ($fb) {
  system("make clean");
  system("make distclean");
  system("rm -R src/.deps");
  unlink("config.cache");
  system("./configure");
}

if (-e "src/gnut") {
  unlink("src/gnut");
}

close STDERR;
open(STDERR, ">&STDOUT");

open(MAKE, "make 2>&1 |");
while($l = <MAKE>) {
  if ($l =~ m/^gcc.*-o gnut/) {
    $l = "gcc -o gnut ...\n";
  } elsif ($l =~ m/^gcc/) {
    $l =~ s/ -c / /;
    $l =~ s/ -DHAVE_ERR_H=1 / /;
    $l =~ s/ -DHAVE_FCNTL=1 / /;
    $l =~ s/ -DHAVE_FLOCK=1 / /;
    $l =~ s/ -DHAVE_GETHOSTNAME=1 / /;
    $l =~ s/ -DHAVE_GETOPT_H=1 / /;
    $l =~ s/ -DHAVE_LIBTERMCAP=1 / /;
    $l =~ s/ -DHAVE_PTHREAD_H=1 / /;
    $l =~ s/ -DHAVE_READLINE=1 / /;
    $l =~ s/ -DHAVE_RE_COMP=1 / /;
    $l =~ s/ -DHAVE_REGCOMP=1 / /;
    $l =~ s/ -DHAVE_REGEX_H=1 / /;
    $l =~ s/ -DHAVE_SELECT=1 / /;
    $l =~ s/ -DHAVE_SOCKET=1 / /;
    $l =~ s/ -DHAVE_STRSTR=1 / /;
    $l =~ s/ -DHAVE_STRTOK_R=1 / /;
    $l =~ s/ -DHAVE_TERM_H=1 / /;
    $l =~ s/ -DHAVE_TERMCAP_H=1 / /;
    $l =~ s/ -DHAVE_TERMIO_H=1 / /;
    $l =~ s/ -DHAVE_TERMIOS_FUNCS=1 / /;
    $l =~ s/ -DHAVE_TERMIOS_H=1 / /;
    $l =~ s/ -DHAVE_XMALLOC=1 / /;
    $l =~ s/ -DPACKAGE=..gnut.. / /;
    $l =~ s/ -D_REENTRANT / /;
    $l =~ s/ -DRETSIGTYPE=void / /;
    $l =~ s/ -DSTDC_HEADERS=1 / /;
    $l =~ s/ -DTIME_WITH_SYS_TIME=1 / /;
    $l =~ s/ -DVERSION=..0.4..... / /;
    $l =~ s/ -g / /;
    $l =~ s/ -I. / /g;
    $l =~ s/ -I. / /g; # Do it twice because there are two -I. in a row
    $l =~ s/ -O2 / /;
    $l =~ s/ -Wall / /;
    $l =~ s/ +/ /g;
  } elsif ($l =~ m/^make\[[12]\]/) {
    $l =~ s/^make..../    /;
  } elsif ($l =~ m/^Making/) {
    $l =~ s/^Mak/    Mak/;
  } elsif ($l =~ m/included/) {
    $l = "";
  } elsif ($l =~ m/^         + from/) {
    $l = "";
  } elsif ($l =~ m/ttydefault.*CTRL.*redefined/) {
    $l = "";
  } elsif ($l =~ m/chardefs.*location.*previous/) {
    $l = "";
  }

  if ($l ne "") {
    print "$l";
  }
}
close MAKE;
if (-e "src/gnut") {
  system("cp src/gnut /usr/local/bin");
  print "New version now in /usr/local/bin\n";
} else {
  print "Build failed (no src/gnut created).\n";
}
