#!/bin/bash
#
# (C) Wolfgang Schweer <wschweer@arcor.de>, 2017
# GPL v2+
# Last edit: 2020-10-16
# Use at your own risk

set -e

# usage
if [ -z "$1"  ] ; then
    echo "Use $0 -h or $0 --help for more information"
    exit 0
fi
if [ "$1" = "-h" ]|| [ "$1" = "--help" ] ; then
cat <<EOF

Usage information:

Use uid and cleartext passwords as params:

edu-ldap-from-scratch <first-user uid> <first-user password> <root password>

Please note: the <first-user uid> must be the same as the one used during installation!

The cleartext passwords in debconf are cleared after the script has been run.

To exclude the command containing the passwords from being stored in bash
history, run 'export HISTFILE=/dev/null' just before calling this script.

Be aware that your existing LDAP database and the first user's HOMEDIR gets
deleted! Consider to backup everything; use the script at your own risk.

EOF
    exit 0
fi

TMP=$(mktemp -d)
cp /usr/share/debian-edu-config/passwords_stub.dat $TMP/passwords.dat
cd $TMP
if [ -d /skole/tjener/home0/"$1" ] ; then
    rm -rf /skole/tjener/home0/"$1"
fi

if pdbedit -L -v $1 >/dev/null 2>&1 ; then
    pdbedit -x $1
fi

sed -i s/FIRSTPWD/"$2"/ passwords.dat
sed -i s/ROOTPWD/"$3"/ passwords.dat
mv passwords.dat /var/cache/debconf
rm -rf /var/lib/ldap/*
if [ -e /etc/krb5kdc/stash ] ; then
    rm /etc/krb5kdc/stash
    rm /etc/krb5.keyt*
    rm -f /etc/debian-edu/host-keytabs/*.*
fi
ldap-debian-edu-install
# send mail to first user (initialize /var/mail/<first-user uid>);
# exim4 needs updated LDAP information for this to work.
systemctl restart exim4.service
/usr/share/debian-edu-config/tools/exim4-create-environment
echo
echo "Done. A new Debian Edu LDAP database has been generated from scratch."
echo "Please reboot to make sure that all services are started in the right order."
echo
