#!/bin/bash

# This script takes care of configuring the system to use the eBox Samba
# module. Most of the parts are needed to have a Samba PDC configuration.
#
# TODO: Do the script idempotent
#       User Perl



# don't start samba with its script
update-rc.d -f samba remove

# stop samba 
invoke-rc.d samba stop

# Copy LDAP schemas
cp /usr/share/ebox-samba/*.schema /etc/ldap/schema

# restart users
/etc/init.d/ebox users restart

# create home directories
test -d /home/samba || mkdir /home/samba
test -d /home/samba/users || mkdir /home/samba/users
test -d /home/samba/groups || mkdir /home/samba/groups
test -d /home/samba/profiles || mkdir /home/samba/profiles
test -d /home/samba/netlogon || mkdir /home/samba/netlogon

# Copy ldap.secret
cp /var/lib/ebox/conf/ebox-ldap.passwd /etc/ldap.secret
chmod 600 /etc/ldap.secret

# regenerate slapd.conf
/usr/share/ebox-usersandgroups/ebox-init-ldap genconfig
        
# restart slapd
/etc/init.d/slapd restart

# Give some time to ldap to start
sleep 1

# add mandatory items to domain database
/usr/share/ebox-samba/ebox-samba-ldap populate-ldap

# update current users in ldap database
/usr/share/ebox-samba/ebox-samba-ldap update-users

# generate smb.conf and ldap.conf
/usr/share/ebox-samba/ebox-samba-ldap genconfig

# update current ldap database
/usr/share/ebox-samba/ebox-samba-ldap update-pdc

# Add quota support to fstab. It's set up for "/home" if exists,
# otherwise we fall back to "/". Remount partition and
# and turn quotas on

perl -e '
open(FD, "/etc/fstab") or die "Could not open /etc/fstab";
my @fstab = <FD>; 
close(FD);
my $home = undef;
my $root = undef;
my $num = -1;
for $line (@fstab) {
    $num++;
    my @fields = split(/[\t\s]+/, $line);
    next if ($fields[0] =~ /^#.*/);
    if ($fields[1] =~ /^\/$/) {
        $root = $num;
    } elsif ($fields[1] =~ /^\/home$/){
        $home = $num;
    }
}
my $line = $home ? $home : $root;
my $mount;
if ($line) {
    my @fields = split(/[\t\s]+/, $fstab[$line]);	
    $mount = $fields[1];
    if ($fstab[$line] =~ /usrquota/) {
        print "Fstab already set up to use quotas\n";
        exit 0;
    } else {
        my $t = $fields[3];
        $fstab[$line] =~ s/$t/$t,usrquota,grpquota/;
    }
} else {
    print "Could not find / or /home mounting points";
    exit 1;
}

open(FD, ">/etc/fstab") or die "Could not write on  /etc/fstab";
print FD  @fstab;
close(FD);
system("/bin/mount -o remount $mount");
exit 0;
';


/usr/share/ebox-samba/ebox-samba-ldap fix-sids

# Change nsswitch.conf to use ldap
for i in passwd group shadow; do
   if ! grep "^$i:.* ldap" /etc/nsswitch.conf >/dev/null; then
       sed  -i -e "s/^\($i:.*\)/\1 ldap/" /etc/nsswitch.conf;
   fi	
done       


invoke-rc.d quota restart 

invoke-rc.d ebox samba restart

