#!/usr/bin/perl -w

use strict;
my %fileseen = ();
my @errno = ();

sub scanfile($);

sub scanfile($) {
  my $file = shift;
  my %todo = ();

  if ($fileseen{$file}) { return ; }
  $fileseen{$file} = 1;

  #print "$file\n";
  if (open(FH, $file)) {
    #print "$file ok\n";
  } else {
    my $f =`find  /usr/include/ -type f | grep $file`;
    chomp $f;
    $file = $f;
    -r "$file" || return;
    if (open(FH, $file)) {
      # ok
    } else {
      #print(" File: $file, open failure\n");
      `echo File: $file, open failure > /dev/tty`;
      return;
    }
  }
  #print " File: $file\n";

  while (<FH>) {
    if (m/^\#[ \t]*include[ \t]+<(.*)>/) {
      $todo{$1} = 1;
    } elsif (m/^\#[ \t]*define[ \t]+(E[A-Z_]+)[ \t]+(\d+)/) {
      $errno[$2] = $1;
    }
  }

  for $file (keys %todo) {
    scanfile($file);
  }
}

chdir "/usr/include";
for my $file (@ARGV) {
  scanfile($file);
}

my $len = 0;
my $ix;
my $jx;
my $val;
my $blanks = "                                       ";
for ($ix = 0; $ix < @errno; $ix++) {
  $val = $errno[$ix];
  if (defined($val)) {
    my $t = length($val);
    $len = $t if ($t > $len);
  }
}
print STDERR "/***********************************************************************
 *
 * Copyrigth: Karl Hammar, Aspö Data, LGPL
 *
 */

#ifndef __ASPO_LOG_ERRNAMES_H__
#define __ASPO_LOG_ERRNAMES_H__

/*
  a programmers alternative to sys_errlist[]
  e.g.: log_errnames[11] == \"EAGAIN\"
 */
#define LOG_ERRORLEN $len
#define LOG_ERRNAMESZ $ix
extern const char *log_errnames[];

#endif
";

print "/***********************************************************************
 *
 * Copyrigth: Karl Hammar, Aspö Data, LGPL
 *
 */

const char *log_errnames[] = {\n";
for ($ix = 0, $jx = 0; $ix < @errno; $ix++, $jx++) {
  $val = $errno[$ix];

  if ($jx >= 5) {
    my $end = $ix-1;
    my $sta = $ix - $jx;
    printf "\t\t/* %3d - %3d */\n", $sta, $end;
    $jx = 0;
  }
  if ($ix % 50 == 0 && $ix > 0) { print "\n"; }
  printf "   " if ($jx == 0);
  if (defined($val)) {
    my $t = 1 + $len - length($val);
    print "\"$val\",", substr($blanks, -$t);
  } else {
    print "\"\",", substr($blanks, -1-$len);
  }
}
for (; $jx <= 5; $jx++) {
  print substr($blanks, -$len);
}
my $end = $ix-1;
my $sta = $ix - $jx;
printf "\t\t/* %3d - %3d */\n", $sta, $end;
print "};\n";
