#!/usr/local/bin/perl

use ExtUtils::MakeMaker;
use IO::File;
use Getopt::Long;

my %opt = (prompt => 1);

GetOptions(\%opt, qw(prompt!));

my $config;

foreach (keys %INC)
 {
  last if ($config = $_) =~ s/^IO(.)File/Net$1Config/;
 }

defined($config) && -f $config
	? require $config
	: eval { require Net::Config };

my %config = ();

%config = %Net::Config::NetConfig
	if defined %Net::Config::NetConfig;

my $def;

sub config_host_list
{
 my($key,$name) = @_;

 my $def = exists $config{$key} ? join(" ", @{$config{$key}}) : "";
 my $val = $opt{prompt}
		? prompt("Enter a list of avaliable $name Hosts :",$def)
		: $def;
 my $res = [];

 $val =~ s/(\A\s+|\s+\Z)//g;

 @$res = split(/\s+/, $val)
	if(length $val);

 $config{$key} = $res;
}

sub config_host
{
 my($key,$name) = @_;

 my $def = exists $config{$key} ? $config{$key} : "";
 my $val = $opt{prompt}
		? prompt("Enter your $name :",$def)
		: $def;

 $config{$key} = ($val =~ /(\S+)/)[0];
}

print "\n\nThe following questions all require a list of host names,\n"
         ."separated with spaces. If you do not have a host avaliable\n"
         ."for any of the services, then enter a single space, followed\n"
         ."by <CR>. To accept the default, hit <CR>\n\n" if $opt{prompt};

config_host_list(qw(NNTP_Hosts NNTP));
config_host_list(qw(SMTP_Hosts SMTP));
config_host_list(qw(POP3_Hosts POP3));
config_host_list(qw(SNPP_Hosts SNPP));
config_host_list(qw(PH_Hosts PH));

print "\n\nThe following questions all require a single host name\n"
          ."If you do not have a host avaliable for any of the services,\n"
          ."then enter a single space, followed by <CR>\n\n" if $opt{prompt};

config_host('FTP_FireWall', 'FTP firewall host name');
config_host('INET_Domain', 'local internet domain name');


my $fh = IO::File->new($config, "w") or
		die "Cannot create `$file': $!";

print "Creating $config ...\n";

$fh->print("# This file was autogenerated by $0\n");
$fh->print("# Any modifications made here will be lost\n");
$fh->print("# ",`date`);

$fh->print(<<'ESQ');

package Net::Config;

require Exporter;
use vars qw(@ISA @EXPORT %NetConfig);
use strict;

@EXPORT = qw(%NetConfig);
@ISA = qw(Exporter);

%NetConfig = (
ESQ

my($k,$v);
while(($k,$v) = each %config)
 {
  my($r,$rv);

  next unless defined $v;

  if(ref($v))
   {
    my @r = grep { length } map { (/(\S+)/)[0] } @$v;
#    next unless @r;
    $rv = join(" ", @{$v});
    $r = @r ? '[qw(' . $rv . ')]' : '[]';
   }
  else
   {
    $rv = ($v =~ /(\S+)/)[0];
#    next unless length $rv;
#    $r = '"' . $rv . '"';
    $r = length($rv) ? '"' . $rv . '"' : 'undef';
   }

  print STDERR sprintf(" %-16s => %s\n",$k,$rv);

  $fh->printf(" %-16s => %s,\n",$k,$r);
 }

$fh->print( ");\n\n1;\n" );
$fh->close;
