#!/bin/sh -


brukernavn=$1
maildir=$(ssh -q atmail1 doveadm user "$brukernavn"|grep home|cut -d: -f2|tr -d \ )
domene=$(echo $brukernavn | cut -d@ -f2)
localpart=$(echo $brukernavn | cut -d@ -f1)


echo Migrating:
echo "          email:   ==${brukernavn}"==
echo "          user:    ==${localpart}"==
echo "          domain:  ==${domene}"==
echo "          maildir: ==${maildir}"==
echo ""

test -z "$brukernavn" && exit 1
test -z "$localpart" && exit 1
test -z "$domene" && exit 1
test -z "$maildir" && exit 1

echo -n "Diskusage: "
du -hs "$maildir"
echo ""

ls -aF "$maildir"

echo ====== Doing initial sync, twice since the first sync probably took a while ======
echo Running first sync..
dsync -v -u "$brukernavn" mirror maildir:"$maildir"
echo done, dsync exitcode=$?
echo Running second sync. Shouldn\'t change much..
dsync -v -u "$brukernavn" mirror maildir:"$maildir"
dsyncexit=$?
if test $dsyncexit -eq 0 || test $dsyncexit -eq 0
then
        echo done, dsync exitcode=$dsyncexit
else
        echo DSYNC Failed. Exiting. FIXME
        exit 1
fi

echo ====== Building up ldif ========================================
cat <<EOF > /tmp/switch-to-mdbox.ldif
dn: uid=$localpart,ou=people,o=$domene,o=ISP,o=example,c=NO
changetype: modify
add: mailLocation
mailLocation: mdbox:~/mdbox
-
delete: mailMessageStore
-

EOF

cat /tmp/switch-to-mdbox.ldif


echo ====== Modifying ldap database ======
ldapmodify -x -h maildb3.example.net -p 389 -D "uid=atmailsync,ou=Special Users,o=example,c=NO" -w superseecret -f /tmp/switch-to-mdbox.ldif -c


echo ====== Clearing auth cache and kicking out the user if he\'s logged in ======
dsh pkill -HUP -u dovecot -f dovecot/auth 
dsh doveadm kick "$brukernavn"
ssh -q popimap1 pkill -HUP -u dovecot -f dovecot/auth 
ssh -q popimap1 doveadm kick "$brukernavn"
ssh -q popimap2 pkill -HUP -u dovecot -f dovecot/auth
ssh -q popimap2 doveadm kick "$brukernavn"

echo ====== Finalizing by doing a last sync and moving away old maildir =======
dsync -v -u "$brukernavn" mirror maildir:"$maildir"
mv "$maildir" /usr/local/atmail/users/deleted-accounts/

echo "============= DONE ================"