#!/usr/bin/perl
# (C) 2007 Michael Weinberger
# See http://wiki.contribs.org/Dirty_Tools for full documentation

use strict;
use esmith::AccountsDB;
use Getopt::Long;


my %opts;
my $getRes = GetOptions( 
	"unlock"=>\$opts{'unlock'},
);

( my $myself = $0) =~ s/.*\///;
$opts{'unlock'} = ($myself eq 'dt-unlock-account' or $opts{'unlock'}) ? 1 : 0;

my $account=$ARGV[0];

die "Usage: dt-lock-account account\n       dt-unlock-account account\n" if not $account;

if( $account eq 'admin' )
	{
	print "not applicable to account 'admin'\n"; exit -1;
	}
	
my $accountdb = esmith::AccountsDB->open or die "Could not open account db";

my $acct = $accountdb->get($account);


if (not $acct or $acct->prop('type') ne "user")
	{
	print "User '$account' does not exist.\n";
	exit -1;
	}

if( $opts{'unlock'} )
	{
    my $status=system("/usr/bin/passwd", "-u", $account)>>8;
	if( $status==254 )
		{
		print "Account $account has never been assigned a password. Cannot unlock.\n";
		exit -1;
		}
    die "Error running /usr/bin/passwd command to unlock account $account" if $status>0 and $status!=254;
    system("/usr/bin/smbpasswd", "-e", $account) == 0
        or die "Error running /usr/bin/smbpasswd command to unlock account $account";
    $acct->set_prop('PasswordSet', 'yes');
	}
else
	{
	not system("/sbin/e-smith/signal-event", "user-lock", $account)
		or die "Error occurred while locking account '$account'";
	}
