#!/bin/sh

# Some easy means to start/stop the mail spool
if [ -x /etc/init.d/exim ] ; then 
  MTAINIT=/etc/init.d/exim
elif [ -x /etc/init.d/exim4 ] ; then 
  MTAINIT=/etc/init.d/exim4
else
  echo "Unknown MTA, exiting..." 
  exit 9
fi

# Init tree
init_ldap () {
  rm -f /var/lib/ldap/*
  for ldif in \
    /etc/ldap/root.ldif \
    /etc/ldap/netgroup.ldif \
    /etc/ldap/autofs.ldif
  do
      if (PW=`cat /etc/shadow | grep ^root \
             | cut -d':' -f2`; sed s:\$ROOTPW:$PW:) < $ldif \
          | /usr/sbin/slapadd
      then
          :
      else
          echo "error: Unable to load $ldif"
          exit 1
      fi
  done
}

set -e

# Create ldap-tree on the initial install
$MTAINIT stop
/etc/init.d/slapd stop

if slapcat \
  |grep 'dn: cn=all-hosts,ou=Netgroup,dc=skole,dc=skolelinux,dc=no' \
  >/dev/null 2>&1
then
  echo "Found existing data: skiping initalization"
else
  init_ldap

  # Add the samba-admin user
  # Dont try if you dont have the samba restart script
  [ -x /etc/init.d/samba ] && /usr/bin/samba-debian-edu-admin
fi

# Restart ldap server
/etc/init.d/slapd start

chown mail.mail /var/lib/maildirs/
$MTAINIT start
