#!/bin/bash

eval "$(ucr shell)"

set -x

die () {
	echo $@
	univention-ldapsearch -LLL '(|(uid=louis.sattel)(uid=aki.sipker))' memberOf ucsschoolSchool; univention-adsearch '(|(cn=louis.sattel)(cn=aki.sipker))' memberof
	exit 1
}

in_groups () {
	local group="$1"
	local user="$2"
	univention-ldapsearch "(&(objectClass=ucsschoolGroup)(cn=$group))" | grep "uid=$user"
	in_ucs=$?
	univention-adsearch "cn=$group" | grep "CN=$user"
	in_ad=$?
	test $in_ad -eq 0 && test $in_ucs -eq 0 && return 0
	return 1
}


udm users/user remove --dn "uid=louis.sattel,cn=schueler,cn=users,ou=schule1,$ldap_base" || true
udm users/user remove --dn "uid=louis.sattel,cn=schueler,cn=users,ou=DEMOSCHOOL,$ldap_base" || true
udm users/user remove --dn "uid=aki.sipker,cn=schueler,cn=users,ou=schule1,$ldap_base" || true
udm users/user remove --dn "uid=aki.sipker,cn=schueler,cn=users,ou=DEMOSCHOOL,$ldap_base" || true

sleep 60
echo "" > /var/log/univention/connector.log
/etc/init.d/univention-ad-connector restart
/usr/share/ucs-school-import/scripts/reset_schema_counter -u -w

for group in schueler-schule1 demoschool-1a schueler-demoschool schule1-1a; do
	in_groups "$group" 'louis.sattel' && die 'in groups'
	in_groups "$group" 'aki.sipker'&& die 'in groups'
done

# /usr/share/ucs-school-import/scripts/ucs-school-testuser-import --student 2 --class 1 DEMOSCHOOL
cat <<-EOF >"/opt/demoschool.csv"
"Schulen","Benutzertyp","Vorname","Nachname","Klassen","Beschreibung","Telefon","EMail"
"DEMOSCHOOL","student","Louis","Sattelmeyer","DEMOSCHOOL-1a","A student.","+04-922-624603",""
"DEMOSCHOOL","student","Aki","Sipker","DEMOSCHOOL-1a","A student.","+24-524-813064",""
EOF

# import to demoschool
/usr/share/ucs-school-import/scripts/ucs-school-user-import -v -c /usr/share/ucs-school-import/configs/ucs-school-testuser-import.json -i /opt/demoschool.csv
sleep 60

for group in schueler-schule1 schule1-1a; do
	in_groups "$group" 'louis.sattel' && die 'in groups'
	in_groups "$group" 'aki.sipker' && die 'in groups'
done
for group in demoschool-1a schueler-demoschool; do
	in_groups "$group" 'louis.sattel' || die 'in groups'
	in_groups "$group" 'aki.sipker' || die 'in groups'
done

# move to schule1
cat <<-EOF >"/opt/demoschool.csv"
"Schulen","Benutzertyp","Vorname","Nachname","Klassen","Beschreibung","Telefon","EMail"
"schule1","student","Louis","Sattelmeyer","schule1-1a","A student.","+04-922-624603",""
"schule1","student","Aki","Sipker","schule1-1a","A student.","+24-524-813064",""
EOF
/usr/share/ucs-school-import/scripts/ucs-school-user-import -v -c /usr/share/ucs-school-import/configs/ucs-school-testuser-import.json -i /opt/demoschool.csv
sleep 60

for group in schueler-schule1 schule1-1a; do
	in_groups "$group" 'louis.sattel' || die 'in groups'
	in_groups "$group" 'aki.sipker' || die 'in groups' 
done
for group in demoschool-1a schueler-demoschool; do
	in_groups "$group" 'louis.sattel' && die 'in groups'
	in_groups "$group" 'aki.sipker' && die 'in groups'
done


echo "OK"
