#!/bin/bash

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



# stop samba
stop smbd
stop nmbd

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

# create home directories
test -d /home/samba || mkdir /home/samba
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

# 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 $type = $fields[2];
        my $t = $fields[3];
        my $attrs = "usrquota,grpquota";
        unless ($type eq "xfs") {
            $attrs .= ",acl";
        }
        $fstab[$line] =~ s/$t/$t,$attrs/;
    }
} 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

# This might fail if the fs does not support quotas
invoke-rc.d quota restart

exit 0
