#!/usr/bin/perl -w

{
    use strict;
    use warnings;
    use esmith::ConfigDB;

    my $configDB    = esmith::ConfigDB->open_ro or die("can't open Config DB");
    my $dbKey       = 'ipsec';
    my $systemMode  = $configDB->get("SystemMode")->value;
    my $ipsecStatus = $configDB->get_prop( $dbKey, 'status' ) || 'disabled';

    if ( $systemMode ne 'servergateway' ) {
        $OUT .= "# System not in Server Gateway mode\n";
    }

    elsif ( $ipsecStatus ne 'enabled' ) {
        $OUT .= "# Ipsec not enabled\n";
    }

    else {
        my $ipsecDB = esmith::ConfigDB->open_ro('ipsec_connections')
          or die("cant connect to ipsec database");

        my $dbKey = 'ipsec';

        # Generic setup file
        my $debugstatus = $configDB->get_prop( $dbKey, 'debug' ) || 'none';

        # A standard config is included in the RPM but we need to generate a new one so we can modify settings

        $OUT .= "config setup\n";
        $OUT .= "    protostack=netkey\n";
        $OUT .= "    plutodebug=$debugstatus\n";
        $OUT .= "    #klipsdebug=none\n";
        $OUT .= "    plutostderrlog=/var/log/pluto/pluto.log\n";
        $OUT .= "    dumpdir=/var/run/pluto/\n";
        $OUT .= "    nat_traversal=yes\n";

        # This should get all the connections in an array

        my @connections = $ipsecDB->keys;

        $OUT .= "    virtual_private=";

        my $virtual_private = '';

        foreach my $ipsecprop (@connections) {

            my $type = $ipsecDB->get_prop( "$ipsecprop", 'type' );
            print "Connection: $ipsecprop Type: $type\n";

            if ( $type eq "ipsec" ) {
                print "Connection: $ipsecprop\n";
                my $ipsecstatus = $ipsecDB->get_prop( "$ipsecprop", 'status' ) || "disabled";

                if ( $ipsecstatus eq "enabled" ) {
                    my $subnet = $ipsecDB->get_prop( "$ipsecprop", 'rightsubnet' );
                    $virtual_private .= "%v4:$subnet,";
                }

                # End if
            }

            # End foreach
        }

        # Remove last character ','
        chop($virtual_private);
        $OUT .= "$virtual_private\n";
        $OUT .= "\n";
        $OUT .= "include /etc/ipsec.d/ipsec.conf\n";

        # End else
    }

    # End
}

