#!/usr/bin/perl -w
#----------------------------------------------------------------------
# copyright (C) 1999-2005 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;

my $event = $ARGV [0];
my $userName = $ARGV [1];

#------------------------------------------------------------
# Check the Unix account
#------------------------------------------------------------


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

my @users;
if ($event eq 'post-upgrade')
{
    @users = $a->users;
}
else
{
    die "Username argument missing." unless defined ($userName);
    my $u = $a->get($userName) or die "No account db record found for user $userName";
    @users = ($u);
}
foreach my $u (@users)
{
    my $type = $u->prop('type');
    my $userName = $u->key;

    die "Account $userName is not a user account; modify user failed.\n"
	unless ( ($userName eq 'admin') or ($type eq 'user') );

    setpwent;
    my ($comment, $shell) = (getpwnam($userName))[5,8];
    endpwent;
    my $new_shell = $u->prop('Shell')
		|| (($shell eq "/bin/sshell") ? "/usr/bin/rssh" : $shell);

    $u->set_prop('Shell', $new_shell);

    #------------------------------------------------------------
    # Modify user's shell, if required, in /etc/passwd using "usermod"
    #------------------------------------------------------------
    unless ($shell eq $new_shell)
    {
	system("/usr/sbin/usermod", '-s', "$new_shell", $userName) == 0
	    or die "Failed to modify shell of account $userName.\n";
    }

    #------------------------------------------------------------
    # Modify user's first name and last name if required,
    # in /etc/passwd using "usermod"
    #------------------------------------------------------------
    my $first = $u->prop('FirstName') || "";
    my $last = $u->prop('LastName') || "";
    my $new_comment = "$first $last";

    unless ($comment eq $new_comment)
    {
	system("/usr/sbin/usermod", "-c", "$first $last", $userName) == 0
	    or die "Failed to modify comment of account $userName.\n";
    }
}

exit (0);
