#!/usr/bin/perl -w

require DebianNet;

@services = qw(https spop3 ssmtp snews ssl-ldap simap);

$| = 1;

print "\n############ Stunnel configuration program\n\n";

$"=',';
print "Insert service name (@services): ";
$service = <> || exit(1);
chomp $service;
$service =~ s/^\s*//;
$service =~ s/\s*$//;
if ( $service eq '') {
	die "You must give a service name.\n";
}

unless ( `grep ^$service /etc/services 2>/dev/null` ) {
	warn "Service $service not present in /etc/services.\n";
	warn "It's better if you add it before continuing.\n";
	warn "Hit [ENTER] to continue or Cntrl-C to stop.\n";
	<>;
}

print "Insert program name: ";
$program = <> || exit(1);
chomp $program;

$program =~ s/^\s*//;
$program =~ s/\s*$//;
if ( $program eq '') {
	die "Must have a valid program to run.\n";
}
if ( $program =~ /^\@(.+:.+)$/) { # port redirection
	$base = $1;
} else { # daemon
	$bin = (split(/\s/, $program))[0];
	$bin =~ m|/?([^/]+)$|;
	$base = $1;
}

# print "Base: $base\n";

$cert = "/usr/lib/ssl/certs/$base.pem";

unless (-f $cert) {
	print "Generate certificate for $base? [Y/n]: ";
	$ans = <> || exit(1);
	if ( $ans =~ /^y?$/i ) {
		$cmd = "umask 0007 && /usr/bin/ssl/ssleay req -new -x509 -nodes " .
			"-out $cert -days 365 -keyout $cert";
		print "Running: $cmd\n";
		system($cmd);
	}
} else {
	print "Using existing certificate: $cert.\n";
}

$entry = "$service stream  tcp  nowait  root  /usr/sbin/stunnel $program";

print "I will add the following entry to /etc/inetd.conf:\n\n$entry\n\n";
print "Is it ok? [Y/n]: ";
$ans = <> || exit(1);

if ( $ans =~ /^y?$/i ) {
	DebianNet::add_service($entry);
} else {
	print "Service not added\n";
}

