#!/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 esmith::AccountsDB;
use utf8;
use esmith::util::ldap;

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);
}

# prepare LDAP bind
my $ldap=esmith::util::ldap->new();

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->ldapdeluser($ibay);
$result && ( $x = $ldapauth ne 'enabled' ? $x : 255, warn "Failed to delete (ldap) ibay account $ibay.\n" );

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

exit $x
