#!/usr/bin/perl -w

use strict;
use Cwd;

my $pwd = getcwd;
my $dirname = $pwd;
$dirname =~ s#.*/##;

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst)
= localtime(time);
my $today = sprintf('%04d-%02d-%02d', 1900 + $year, 1 + $mon, $mday);

my $cflags = '-Wall -O2';
my $arch = `uname -m`;
chomp $arch;
if ($arch eq 'alpha')
{
  $cflags = '-Wall -O1';
}
elsif ($arch ne 'ppc' && $arch ne 'sparc64')
{
  $arch = 'i386';
  $cflags .= ' -march=i586';
}

my $cmd = 'readelf -l /bin/sh';
my $elfbase;
open(CMD, $cmd . '|') || die $cmd . ": $!";
while(<CMD>)
{
  if (m/^\s*LOAD\s+/)
  {
    my @number = split;

    # On FreeBSD/alpha the base address is a 64-bit address above 4GB.
    # At least one such machine runs a perl with 32-bit integer arithmetic. 
    # Thus we must handle the value as a string, not a number.
    $elfbase = $number[2];
    last;
  }
}
close CMD;
die $cmd . ' returned no result.' if (!defined($elfbase));

my $elfmagic = $elfbase;
die "Last digit of ELF base address ($elfbase) is not zero"
unless ($elfmagic =~ s/0$/1/);

open(OUTPUT, '> config.mak') || die "$!";
select OUTPUT;
printf "PWD=%s\n", $pwd;
printf "DIRNAME=%s\n", $dirname;
printf "HTML=file://%s/_html/index.html\n", $pwd;
printf "DVI=file://%s/_dvi/%s.dvi\n", $pwd, $dirname;
printf "TODAY=%s\n", $today;
printf "ARCH=%s\n", $arch;
printf "CFLAGS=%s\n", $cflags;
printf "OUT=out/%s\n", $arch;
printf "ELFBASE=%s\n", $elfbase;
printf "ELFMAGIC=%s\n", $elfmagic;
