#!/usr/bin/perl

#----------------------------------------------------------------------
# copyright (C) 2024 Koozali foundation inc.
#		
# 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
# 
#----------------------------------------------------------------------

#------------------------------------------------------------
# Delete the Unix account and files for the ibay.
#------------------------------------------------------------
package esmith;

use strict;
use Errno;
use esmith::ConfigDB;
use esmith::util;
use Net::LDAP;
use esmith::AccountsDB;

my $adb = esmith::AccountsDB->open_ro();

my $conf = esmith::ConfigDB->open_ro or die "Could not open config db";

unless ($conf->get('ldap')->prop('status') eq "enabled" )
{
    warn "Not running action script $0, LDAP service not enabled!\n";
    exit(0);
}

my $domain = $conf->get('DomainName')
    || die("Couldn't determine domain name");
$domain = $domain->value;

# prepare LDAP bind
my $pw = esmith::util::LdapPassword();
my $base = esmith::util::ldapBase ($domain);

my $ldap = Net::LDAP->new('localhost')
    or die "$@";

$ldap->bind(
    dn => "cn=root,$base",
    password => $pw
);


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

die "Username argument missing." unless defined ($ibay);
$a = $adb->get($ibay) || undef;
unless ( defined $a && $a->prop('type') eq "ibay-deleted" )
{
    warn "$ibay is not an Ibay account\n";
    exit (0);
}

my $ldapauth = $conf->get('ldap')->prop('Authentication') || 'disabled';
my $x = 0; # exit value


my $discard = `/bin/rm -rf /home/e-smith/files/ibays/$ibay`;
if ($? != 0)
    {
        ( $x = 255, warn "Failed to delete content of ibay $ibay.\n" );
    }

if ( "$ldapauth" ne "enabled" )
{
    $discard = `/usr/sbin/userdel "$ibay"`;
    if ($? != 0)
    {
        ( $x = 255, warn "Failed to delete (unix) account $ibay.\n" );
    }
}

my $result = $ldap->delete("uid=$ibay,ou=Users,$base");
$result->code && ( $x = $ldapauth ne 'enabled' ? $x : 255, warn "Failed to delete (ldap) ibay account $ibay.\n" );

$result = $ldap->delete("cn=$ibay,ou=Groups,$base");
$result->code && ( $x = $ldapauth ne 'enabled' ? $x : 255, warn "Failed to delete (ldap) group account $ibay.\n" );

exit $x
