#!/bin/bash

echo "Set kelvin to single process to make sure we always hit the same cache (the cache is not shared between processes)"
univention-app configure ucsschool-kelvin-rest-api --set ucsschool/kelvin/processes=1
univention-app restart ucsschool-kelvin-rest-api
echo "sleep"
sleep 5


UCSFQDN="$(hostname -f)"
UCSADM="Administrator"
UCSPW="univention"
IP="$(ucr get interfaces/eth0/address)"
PROTO="https"
TOKEN=$(curl -i -k -X POST $PROTO://$UCSFQDN/ucsschool/kelvin/token \
        -H "Content-Type:application/x-www-form-urlencoded" \
        -d "username=$UCSADM" \
        -d "password=$UCSPW" 2>/dev/null \
        | tail -1 | cut -f2- -d: | cut -f2 -d\")
echo "Token: $TOKEN"


NUMBER="01"
cat << EOF > /tmp/create_user_$NUMBER.json
{"name": "lehrer.$NUMBER", "ucsschool_roles": ["teacher:school:demoschool"], "school": "https://$IP/ucsschool/kelvin/v1/schools/demoschool", "firstname": "Lehre", "lastname": "$NUMBER", "password": "univention", "record_uid": "lehrer.$NUMBER", "roles": ["https://$IP/ucsschool/kelvin/v1/roles/teacher"], "school_classes": {}, "workgroups": {}, "source_uid": "kelvin_bug"}
EOF

curl -v -i -k "$PROTO://$IP/ucsschool/kelvin/v1/users/" \
    -H "accept: application/json" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "$(< /tmp/create_user_$NUMBER.json)"
echo

NUMBER="02"
cat << EOF > /tmp/create_user_$NUMBER.json
{"name": "lehrer.$NUMBER", "ucsschool_roles": ["teacher:school:demoschool"], "school": "https://$UCSFQDN/ucsschool/kelvin/v1/schools/demoschool", "firstname": "Lehre", "lastname": "$NUMBER", "password": "univention", "record_uid": "lehrer.$NUMBER", "roles": ["https://$UCSFQDN/ucsschool/kelvin/v1/roles/teacher"], "school_classes": {}, "workgroups": {}, "source_uid": "kelvin_bug"}
EOF

curl -v -i -k "$PROTO://$UCSFQDN/ucsschool/kelvin/v1/users/" \
    -H "accept: application/json" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "$(< /tmp/create_user_$NUMBER.json)"
echo

echo "clear cache, the same request will work again"
echo "ucsschool-kelvin-rest-api restart"
univention-app restart ucsschool-kelvin-rest-api
echo "sleep"
sleep 5

NUMBER="02"
cat << EOF > /tmp/create_user_$NUMBER.json
{"name": "lehrer.$NUMBER", "ucsschool_roles": ["teacher:school:demoschool"], "school": "https://$UCSFQDN/ucsschool/kelvin/v1/schools/demoschool", "firstname": "Lehre", "lastname": "$NUMBER", "password": "univention", "record_uid": "lehrer.$NUMBER", "roles": ["https://$UCSFQDN/ucsschool/kelvin/v1/roles/teacher"], "school_classes": {}, "workgroups": {}, "source_uid": "kelvin_bug"}
EOF

curl -v -i -k "$PROTO://$UCSFQDN/ucsschool/kelvin/v1/users/" \
    -H "accept: application/json" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "$(< /tmp/create_user_$NUMBER.json)"
echo
