#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2001-2006 Mitel Networks Corporation
# 
# 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
#----------------------------------------------------------------------

package esmith;

use strict;
use Errno;
use esmith::AccountsDB;
use esmith::ConfigDB;
use IO::File;
use English;

my $a = esmith::AccountsDB->open or die "Could not open accounts db";
my $conf = esmith::ConfigDB->open or die "Could not open configuration db";

my $event = $ARGV [0];

my @users_to_lock = bad_password_users();

defined $ARGV[1] && push @users_to_lock, $ARGV[1];

for my $user (@users_to_lock)
{
    lock_user($user);
}

exit 0;

sub lock_user
{
    my ($userName) = @_;
    #------------------------------------------------------------
    # Lock the user account in all authentication databases
    #------------------------------------------------------------

    my $u = $a->get($userName) or die "No account record for user $userName";

    system("/usr/bin/passwd", "-l", $userName) == 0
        or die "Error running /usr/bin/passwd command to lock account $userName";
    system("/usr/bin/smbpasswd", "-d", $userName) == 0
        or die "Error running /usr/bin/smbpasswd command to lock account $userName";
    $u->set_prop('PasswordSet', 'no');

    if ($userName eq 'admin')
    {
        $conf->set_value('PasswordSet', 'no');
    }
}

sub bad_password_users
{
    my $smbpasswd = IO::File->new("/etc/samba/smbpasswd", '<')
        or die "Can't open smbpasswd: $OS_ERROR\n";

    my @users;

    SMBPASSWD:
    while (my $smb_entry = <$smbpasswd>)
    {
        my ($user, $uid, $lanman_hash, $nt_hash, @rest) 
            = split /:/, $smb_entry;

        if (   $lanman_hash eq "AAD3B435B51404EEAAD3B435B51404EE"
            or $nt_hash     eq "31D6CFE0D16AE931B73C59D7E0C089C0"
           )
        {
            push @users, $user;
            next SMBPASSWD;
        }
    }

    $smbpasswd->close;
    return @users;
}
