#!/usr/bin/perl  -w
#==============================================================================
# lat-pptp
# ========
# 0.9.0 (2004-09-08)
# (c)2003-2004 Altiplano bvba
#==============================================================================
package esmith;
use strict;
use esmith::db;
use esmith::util;
use Getopt::Long;
use Pod::Usage;
my %conf;
tie %conf, 'esmith::config';
my %accounts;
tie %accounts, 'esmith::config', '/home/e-smith/db/accounts';
my ($Hlp, $Cml, $Inp);

#==============================================================================
#  Main
#==============================================================================
# Analyze commandline options
GetOptions  ("help"           => \$Hlp,
             "command-line=s" => \$Cml,
             "input-file=s"   => \$Inp);

if ( $Hlp ) { &PrintPod(9); exit; }

# What (major) SME version are we running on?
db_get_prop(\%conf, "sysconfig", "ReleaseVersion");
my $MVer = db_get_prop(\%conf, "sysconfig", "ReleaseVersion");
$MVer=substr($MVer,0,1);

# We need one argument or the other, but not both
if (($Cml && $Inp) || (! $Cml && ! $Inp))
	{ &PrintPod(1); exit; }

# Check if pptp is active
if (db_get_prop(\%conf, "pptpd", "status") ne "enabled") {
    print "PPTP was not activated on your server. Please activate it by increasing the\n";
    print "number of PPTP clients in the server-manager (Security / Remote Access).\n\a";
    exit;
}

my @records;
if ($Inp) {
    open(LIST,"< $Inp")  ||  die "Can't find $Inp.\n";
    @records = grep(!/(^\s*#)|(^\s*$)/,<LIST>);
    close(LIST); }
elsif ($Cml) { @records=($Cml); }
else { &PrintPod(1); exit; }
&ExpandWildCard;  # Check for wildcards and expand if necessary

# Process each user
foreach my $record (@records)
{
    my @fields=split(/\|/,$record);
    for (my $cnt=0; $cnt <= $#fields; ++$cnt) { for ($fields[$cnt]) { s/^\s+//; s/\s+$//; }}
    my $username = $fields[0];
    if ( @fields >= 2) {  # Both arguments must be given
        if ((db_get(\%accounts, $username)) &&
            (db_get_type(\%accounts, $username) eq "user")) {

            # Deactivate PPTP
            if ($fields[1] =~ /off/i ) {
                print "Deactivating VPN access for user '$username'.\n";
    		SWITCH: {
	        	($MVer=="5") && do {  
            		    db_set_prop(\%accounts, $username, 'PPTPAccess', "off");
            		    system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                		or die ("An error occurred while updating account '$username'.\n");
			    last SWITCH;
			};
		        ($MVer=="6") && do {
            		    db_set_prop(\%accounts, $username, 'VPNClientAccess', "no");
            		    system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                		or die ("An error occurred while updating account '$username'.\n");
			    last SWITCH;
			};
		        ($MVer=="7") && do {
            		    db_set_prop(\%accounts, $username, 'VPNClientAccess', "no");
            		    system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                		or die ("An error occurred while updating account '$username'.\n");
			    last SWITCH;
			};
                        ($MVer=="8") && do {
                            db_set_prop(\%accounts, $username, 'VPNClientAccess', "no");
                            system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                                or die ("An error occurred while updating account '$username'.\n");
                            last SWITCH;
                        };
                        ($MVer=="9") && do {
                            db_set_prop(\%accounts, $username, 'VPNClientAccess', "no");
                            system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                                or die ("An error occurred while updating account '$username'.\n");
                            last SWITCH;
                        };

		}
            }
            # Activate PPTP
            elsif ($fields[1] =~ /on/i ) {
                print "Activating VPN access for user '$username'.\n";
    		SWITCH: {
	        	($MVer=="5") && do {  
            		    db_set_prop(\%accounts, $username, 'PPTPAccess', "on");
            		    system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                		or die ("An error occurred while updating account '$username'.\n");
			    last SWITCH;
			};
		        ($MVer=="6") && do {
            		    db_set_prop(\%accounts, $username, 'VPNClientAccess', "yes");
            		    system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                		or die ("An error occurred while updating account '$username'.\n");
			    last SWITCH;
			};
		        ($MVer=="7") && do {
            		    db_set_prop(\%accounts, $username, 'VPNClientAccess', "yes");
            		    system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                		or die ("An error occurred while updating account '$username'.\n");
			    last SWITCH;
			};
                        ($MVer=="8") && do {
                            db_set_prop(\%accounts, $username, 'VPNClientAccess', "yes");
                            system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                                or die ("An error occurred while updating account '$username'.\n");
                            last SWITCH;
                        };
                        ($MVer=="9") && do {
                            db_set_prop(\%accounts, $username, 'VPNClientAccess', "yes");
                            system("/sbin/e-smith/signal-event", "remoteaccess-update", $username) == 0
                                or die ("An error occurred while updating account '$username'.\n");
                            last SWITCH;
                        };

        	}
	    }	
            else { print "Unknown argument '$fields[1]' for user $username"; }
        }
        else { print "User '$username' doesn't exist on this server.\n\a"; }
    }
    else { print "We need at least a user name and its VPN access status ('on' or 'off').\n\a"; }
}
#==============================================================================
# Subroutines
#==============================================================================
# Test for wildcards in the username. If any wildecards are found, the array
# @records is expanded with the user names that meet the conditions.
sub ExpandWildCard {
    my $ctrec = 0;
    foreach my $record (@records)
    {
        my @fld=split(/\|/,$record);
        for (my $cnt=0; $cnt <= $#fld; ++$cnt) { for ($fld[$cnt]) { s/^\s+//; s/\s+$//; }}

        if ($fld[0] =~ /\*|\?/) {   # Does it contain the wildcards?
            $fld[0] =~ s/\*/\.\*/g; # Replace * with .* to allow for grep.
            $fld[0] =~ s/\?/\./g;   # Replace ? with . to allow for grep.

            open USRS, "</home/e-smith/db/accounts" or die "Can't open /home/e-smith/db/accounts: $!";
            my @match = grep /^$fld[0]\=user\|/i, <USRS>;
            close(USRS);

            my $cu = 0;
            foreach my $tst (@match) {
                $tst =~ /\=/; $tst = $`;
                for (my $cnt=1; $cnt <= $#fld; ++$cnt) { $tst = $tst." | ".$fld[$cnt]; };
                if ($cu == 0 ) {
                    $records[$ctrec] = $tst;
                    $cu =1;
                }
                else {
                    push(@records, $tst);
                }
            }
        }
        ++$ctrec;
    }
}
#==============================================================================
# Print the pod text as a help screen
sub PrintPod {
    my ($verbose, $message) = @_;
    pod2usage(-verbose => $verbose, -message => $message, -exitval => 64);
}

#==============================================================================

=pod

=head1 NAME

B<lat-pptp> - The lazy administrator\'s tool to (de)activate pptp access

=head1 DESCRIPTION

PPTP access is by default deactivated on Mitel's SME servers (5.x/6.x).
Once activated in the server-manager pannel, you still need to grant or deny 
VPN access to individual users. With lat-pptp you can enable or disable VPN
access on a per-user basis.

In SME 5.6 there is no functional equivalent for lat-pptp in the server-manager.
In SME 6.0 you can find this setting under Collaboration/Users.

See F</usr/doc/lazy-admin-tools/example.pptp> for the format of the input file.

=head1 SYNOPSIS

B<lat-pptp> -c "user | pptpaccess"

B<lat-pptp> -a -i /path/to/pptp.list

=head1 OPTIONS

The following options are supported:

=over 4

=item B<-c "Arguments">, B<--command-line="Arguments">

Take arguments from the command line.
See the 'Arguments' section below for the various arguments that are accepted.

=item B<-h>, B<--help>

Extended help for this tool

=item B<-i FILE>, B<--input-file=FILE>

Use the information from FILE to activaet pptp

=back

=head2 Arguments:

   users*     : Must be an existing account on the server.
                Wildcards (* and ?) are accepted.
   pptpaccess : Either 'on' or 'off'. Default is 'off'.

   * mandatory field

=head1 EXAMPLES

B<lat-pptp -c "harry | on">

Activates pptp for user 'harry'.

B<lat-pptp -c "* | off">

Dectivates pptp for all users on the server.

B<lat-pptp -i /root/pptp.list>

Sets pptp access for the users as defined in F</root/pptp.list>.
Refer to F</usr/doc/lazy-admin-tools/example.users> for an example of an input file.

=head1 SEE ALSO

lat-group(8), lat-pseudonyms(8), lat-ibays(8), lat-quota(8), lat-domains(8), lat-hosts(8), lat-procmail(8), lat-pptp(8), lat-dump(8)

=head1 VERSION

Version 0.9.0 (2004-09-08). The latest version is hosted at B<http://www.contribs.org/contribs/mblotwijk/>

=head1 COPYRIGHT

(c)2003-2004, Altiplano bvba (B<http://www.altiplano.be>). Released under the terms of the GNU license.


=head1 BUGS

Please report bugs to <Bugs@Altiplano.Be>

=cut

#==============================================================================
