#!/usr/bin/perl
#------------------------------------------------------------
#This action generates a special Active Directory user
#to be used for SME Server access to the Active Directory.
#The password for this user will be stored encrypted to
#/etc/samba/AD.pw
#
#Copyright 2014 Koozali Foundation, Inc.
#11/15/2014: G.Zartman <gzartman@koozali.org>
#
#The code contained herein can be distributed under the same
#license as Perl
#
#TO DO:
#
#------------------------------------------------------------
package esmith::thisaction;

use strict;
use warnings;
use esmith::ConfigDB;
use MIME::Base64();

##Pull arguments
my $event = $ARGV [0];
my $AdminPass = $ARGV [1];

die 'Active Directory access error: Missing admin password' unless ($AdminPass);

##Generate an ad_admin password, encrypt it, then write it to /etc/samba/AD.pw
my @set = ('0'..'9','A'..'Z','a'..'z');
my $set = '';
my $pass = join '' => map $set[rand @set], 1..20;

warn "Creating stashed password for ad_admin\n";

my $encrypted_pass = MIME::Base64::encode($pass);
unlink '/etc/samba/AD.pw';
unless ( open( WR, ">/etc/samba/AD.pw" ) ) {
    die "Samba provisioning error: Unable to create Active Directory LDAP password\n";
    return undef;
}
print WR "$encrypted_pass\n";
close WR;
chmod 0600, '/etc/samba/AD.pw';

warn "ad_admin: $pass\n";

##Set ad_admin account to active directory as a domain admin
my $add_admin = "/usr/bin/samba-tool user create " .
                "ad_admin $pass " .
                "-U Administrator\%$AdminPass";
system ($add_admin);
die "Samba provisioning error: Unable to create ad_admin user in Active Directory.\n" if ($? == -1);

my $add_members = "/usr/bin/samba-tool group addmembers " .
                  "\'Domain Admins\' ".
                  "ad_admin " .
                  "-U Administrator\%$AdminPass";
system ($add_members);
die "Samba provisioning error: Unable to add ad_admin user to the Domain Admins group.\n" if ($? == -1);

1;

