#!/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

# Make sure slapd is really stopped
SLAPPIDS=$(pidof slapd || /bin/true)
if [ "$SLAPPIDS" ] ; then 
  echo -n "Warning: slapd is still running, trying to TERM it"
  for SLAPPID in $SLAPPIDS ; do 
    kill $SLAPPID || /bin/true
  done
fi

# Not sure why, but it seem like slapd takes some time to shut down 
LOOP=0
while [ $LOOP -lt 10 ] ; do 
  SLAPPIDS=$(pidof slapd || /bin/true)
  if [ "$SLAPPIDS" ] ; then 
    let LOOP=($LOOP + 1)
    sleep 1
    echo -n "."
  else
    LOOP=10
  fi
done
echo  
if [ "$SLAPPIDS" ] ; then 
  echo -n "Error: slapd is still running, I'll KILL it"
  for SLAPPID in $SLAPPIDS ; do 
    kill -9 $SLAPPID || /bin/true
  done
fi

# Not sure why, but it seem like slapd takes some time to shut down 
LOOP=0
while [ $LOOP -lt 10 ] ; do 
  SLAPPIDS=$(pidof slapd || /bin/true)
  if [ "$SLAPPIDS" ] ; then 
    let LOOP=($LOOP + 1)
    sleep 1
    echo -n "."
  else
    LOOP=10
  fi
done
echo 
if [ "$SLAPPIDS" ] ; then 
  echo "Error: Critical: slapd is still running, I'm giving up"
  exit 9
fi

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 if it aint already running 
# (samba-debian-edu-admin also tries to start slapd)
SLAPPIDS=$(pidof slapd || /bin/true)
if [ -z "$SLAPPIDS" ] ; then 
  /etc/init.d/slapd start
fi

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