#!/usr/bin/perl
# Stefan Tomanek <stefan@pico.ruhr.de>
# updated by Wolfram Sang <ninja@the-dreams.de> on 21.10.06
##
# pcf2vpnc.pl <pcf file> <vpnc config>
##
# 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
#
# $Id: pcf2vpnc 86 2006-10-28 10:41:44Z Dan Villiom Podlaski Christiansen $

use IO::File;
use strict;
use warnings;

sub readPCF($) {
    my ($file) = @_;
    my %config;
    while (<$file>) {
	# Filter unnecessary chars at beginning & end of line
	s/^!*//; s/[\r ]*$//;
	if (/^(.*?)=(.*?)$/) {
	    # We don't need emtpy config strings
	    next if ($2 eq "");
	    if ($1 eq "Host") {
		$config{IPSec}{gateway} = $2;
	    } elsif ($1 eq "GroupName") {
		$config{IPSec}{ID} = $2;
	    } elsif ($1 eq "GroupPwd") {
		$config{IPSec}{secret} = $2;
	    } elsif ($1 eq "enc_GroupPwd") {
		$config{IPSec}{obfuscated} = "secret $2";
	    } elsif ($1 eq "Username") {
		$config{Xauth}{username} = $2;
	    } elsif ($1 eq "UserPassword") {
		$config{Xauth}{password} = $2;
	    } elsif ($1 eq "enc_UserPassword") {
		$config{Xauth}{obfuscated} = "password $2";
	    } elsif ($1 eq "NTDomain") {
		$config{Domain}{""} = $2;
	    } elsif ($1 eq "DHGroup") {
		$config{IKE}{DH} = "Group dh$2";
	    }
	}
    }
    return \%config;
}

sub writeVPNC($) {
    my ($config) = @_;
    my $text = "## generated by pcf2vpnc.pl\n";
    foreach my $section (keys %$config) {
	foreach my $item (keys %{ $config->{$section} }) {
	    $text .= "$section $item ".$config->{$section}{$item}."\n";
	}
    }
    unless (defined $config->{Xauth}) {
	$text .= "\n## To add your username and password,\n";
	$text .= "## use the following lines:\n";
	$text .= "# Xauth username <your username>\n";
	$text .= "# Xauth password <your password>\n";
    }
    return $text;
}

if (defined $ARGV[0]) {
    my $src = new IO::File($ARGV[0]) || die "Unable to open file ".$ARGV[0]."\n";
    if (defined $ARGV[1]) {
	my $dst = new IO::File($ARGV[1], "w") || die "Unable to open file ".$ARGV[1]."\n";
	$dst->write( writeVPNC(readPCF($src)) );
	$dst->close();
	print STDERR "vpnc config written to ".$ARGV[1]."\n";
    } else {
	print writeVPNC(readPCF($src));
	$src->close();
    }
} else {
    print STDERR "Usage: pcf2vpnc.pl <pcf file> [<vpnc file>]\n";
}
