#!/usr/bin/perl -w

package esmith;

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

my $a = esmith::AccountsDB->open_ro || die "Couldn't open accounts db\n";

my $event = $ARGV [0] || die "Event name arg missing\n";;
my @groups;
my @smbgroups;

if ($ARGV[1])
{
    my $groupName = $ARGV [1];
    my $g = $a->get($groupName) ||
		die "Group $groupName not found in accounts db\n";

    my $type = $g->prop('type');
    if ($type =~ /^group/)
    {
        @groups = ($g);
    }
    # Is it a user?
    elsif ($type =~ /^user/)
    {
        # That's fine. We were probably just called from the user-delete
        # event, in which case we want to update all of the groups. So, leave
        # the groups array empty.
        @groups = ();
    }
    else
    {
        die "Expected a user or a group. Got neither: $type\n";
    }
}

# Regenerate all the groups if the previous block failed in some way.
unless (@groups)
{
    @groups = $a->groups;
}

foreach my $group (@groups)
{
    my $groupName = $group->key;
    unless ($group->prop('type') eq 'group')
    {
        warn "Account $groupName is not a group account.\n";
        next;
    }
    my @smbgroups = `/usr/bin/net groupmap list`;
    foreach my $smbgroup (@smbgroups) {
        chomp $smbgroup;
        if ($smbgroup =~ /^.*? \((S-.*)\) -> $groupName$/) {
            system('/usr/bin/net','groupmap','delete',"sid=$1");
        }
    }

    my $description = $group->prop('Description');
    system(
        "/usr/bin/net",
        "groupmap", 
        $description =~ /^Domain (?:Admins|Guests|Users)$/ ? "modify" : "add",
        "ntgroup=$description",
        "unixgroup=$groupName",
        "type=d",
        );
}

@smbgroups = `/usr/bin/net groupmap list`;
foreach my $smbgroup (@smbgroups) {
    chomp $smbgroup;
    if ($smbgroup =~ /^Domain Admins \((S-.*)\) -> -1$/) {
        system('/usr/bin/net','groupmap','modify','ntgroup=Domain Admins','unixgroup=admin','type=d');
    } elsif ($smbgroup =~ /^Domain Users \((S-.*)\) -> -1$/) {
        system('/usr/bin/net','groupmap','modify','ntgroup=Domain Users','unixgroup=shared','type=d');
    } elsif ($smbgroup =~ /^Domain Guests \((S-.*)\) -> -1$/) {
        system('/usr/bin/net','groupmap','modify','ntgroup=Domain Guests','unixgroup=nobody','type=d');
    }
}

exit (0);
