#! /usr/bin/perl -w

# confgen.pl - parses per-link data into config files
#
#    Copyright (C) 2003 Kai Henningsen <kai@debian.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

use strict;

use Data::Dumper;
$Data::Dumper::Useqq = 1;

our (%ep1, %ep2);

require $ARGV[1];

my ($a1, $p1, $a2, $p2) = ($ep1{eadr}, $ep1{eport}, $ep2{eadr}, $ep2{eport});
my ($ad1, $ad2, $pd1, $pd2);
if ($a1 =~ m/(.*)\/dyn$/) {
	$ad1 = 1;
	$a1 = $1;
}
elsif ($a1 eq 'dyn') {
	$ad1 = 1;
	$a1 = '';
}
if ($p1 eq 'dyn') {
	$pd1 = 1;
	$p1 = '';
}
if ($a2 =~ m/(.*)\/dyn$/) {
	$ad2 = 1;
	$a2 = $1;
}
elsif ($a2 eq 'dyn') {
	$ad2 = 1;
	$a2 = '';
}
if ($p2 eq 'dyn') {
	$pd2 = 1;
	$p2 = '';
}

my $cf = $ARGV[0];
my $cft = $cf.'.tmp';

open CONF, '>', $cft or die "$cft: $!";

print CONF "config \"/etc/openvpn/$ARGV[0].local\"\n";
print CONF "config \"/etc/openvpn/$ARGV[2].global\"\n";

print CONF "ca $ARGV[2].crt\n";
print CONF "cert $ep1{name}.crt\n";
print CONF "daemon \"openvpn-$ep2{name}\"\n";
print CONF "dev $ep1{dev}\n" if $ep1{dev};
print CONF "float\n" if $ad2 or $pd2;
print CONF "ifconfig $ep1{iadr}[0] $ep2{iadr}[0]\n" if @{$ep1{iadr}} and @{$ep2{iadr}};
print CONF "key $ep1{name}.key\n";
print CONF "local $a1\n" unless $ad1;
print CONF "lport $p1\n" if $p1;
#print CONF "nobind\n" if $ad1;
print CONF "remote $a2\n" if $a2;
print CONF "replay-persist $cf.persist\n";
print CONF "rport $p2\n" if $p2;
#print CONF "single-session\n" unless $ad2 or $pd2;
print CONF "tls-client\n" if $ep1{tls} eq 'C';
print CONF "tls-server\n" if $ep1{tls} eq 'S';
print CONF "tls-verify \"/usr/share/openvpn/verify-cn $ep2{name}\"\n";
print CONF "up \"/usr/lib/tunneldigger/td-up $ep2{name} '", join(' ', @{$ep1{iadr}}), "' '", join(' ', @{$ep2{nets}}), "'\"\n";
print CONF "hand-window 600\n";

close CONF or die "$cft: $!";
&move_if_changed($cft, $cf);

sub move_if_changed
{
	my ($tmp, $fin) = @_;
	system("cmp -s $tmp $fin || mv -v $tmp $fin");
	unlink $tmp;
}
