#!/usr/bin/perl

use Cwd qw(cwd);

$file=shift || "configure";

if(!open(F,$file))
{
  print STDERR "Error opening $file: $!\n";
  exit(1);
}

my $fixed=0;
my $s=0;
my $buffer="";

while(<F>)
{
  print "[STATUS=$s] $_" if($s>0 && $ENV{DEBUG});
  if($s==0 && m/x86_64.*\|powerpc\*-\*linux\*/) {
    $s++;
  }
  elsif($s==0 && m/powerpc\*\).*dynamic_linker=no/) {
    s/powerpc/xpowerpc/;
    $fixed++;
  }
  elsif($s==1 && m/case.*file.*conftest/) {
    $s++;
  }
  elsif($s==2 && m/\*32-bit\*/) {
    $s++;
  }
  elsif($s==3 && m/powerpc64le-\*linux\*/) {
    $s++;
  }
  elsif($s==3 && m/powerpc64-\*linux\*|ppc64-\*linux\*/) {
    s/powerpc64-\*linux\*/powerpc64-*linux*|powerpc64le-*linux*/;
    s/ppc64-\*linux\*/ppc64-*linux*|ppc64le-*linux*/;
    $fixed++;
    $s++;
  }
  elsif($s==4 && m/\*64-bit\*/) {
    $s++;
  }
  elsif($s==5 && m/powerpcle-\*linux\*/)
  {
    $s++;
  }
  elsif($s==5 && m/powerpc\*-\*linux\*/)
  {
    ($spaces)=m/^(\s*)/;
    s/ppc\*-\*linux\*/ppc-*linux*/;
    s/powerpc\*-\*linux\*/powerpc-*linux*/;
    $fixed++;
    $_=$spaces."powerpcle-*linux*)\n".
       $spaces."  LD=\"\${LD-ld} -m elf64lppc\"\n".
       $spaces."  ;;\n".
       $_;
    $s++;
  }
  elsif(m/rm.*conftest/) {
    $s=0;
  }
  # Fix OR1K _REENTRANT incorrect macro check:
  if(m/ax_pthread_check_macro="_REENTRANT"/) {
    $fixed++;
    ($spaces)=m/^(\s*)/;
    $_=$spaces."if [ \$host_cpu = \"or1k\" ]\n".
       $spaces."then\n".
       $spaces."  ax_pthread_check_macro=\"--\"\n".
       $spaces."else\n".
       $spaces."  ax_pthread_check_macro=\"_REENTRANT\"\n".
       $spaces."fi\n";
  }
  $buffer.=$_;
}
close(F);
if($fixed) {
  if(!open(W,">$file")) {
    print STDERR "Error opening file $file for writing: $!\n";
    exit(2);
  }
  print W $buffer;
  close(W);
  print "$file fixed ($fixed)\n";
}
else {
  $dir=cwd;
  open(F,">>/root/no_fix_configure.txt");
  print F scalar(localtime)." - $dir/$file\n";
  close(F);
  print "** WARNING: fix_configure no more needed for $dir/$file **\n";
}
