#!/bin/bash

set -e

if [ -f /etc/eole/samba4-vars.conf ]; then
    . /etc/eole/samba4-vars.conf
else
    . /var/lib/lxc/addc/rootfs/etc/eole/samba4-vars.conf
fi

if [ "$AD_TYPE" = "scribe" ]; then
    function CreoleRun () {
        lxc-attach -n addc -- $1
    }
fi

# retrieve the list of machines in AD
machins=$(CreoleRun "ldbsearch -H /var/lib/samba/private/sam.ldb objectClass=computer dNSHostName" "addc"|grep "^dNSHostName: "|cut -d " " -f 2| while read machin; do
  if [ "$NOM_DOMAINE_MACHINE" = "$machin" ] || [ "$AD_SERVER_FULLNAME" = "$machin" ]; then
    continue
  fi
  echo -n " '$machin',"
done)


# build reactor SLS
echo """{% if 'act' in data and data['act'] == 'denied' and data['id'] in [$machins ] %}
renew_key:
  wheel.key.delete:
    - match: {{ data['id'] }}
  wheel.key.accept:
    - include_denied: true
    - match: {{ data['id'] }}
{% endif %}""" > /tmp/autoaccept.sls

# apply it if different
diff -q /tmp/autoaccept.sls /srv/reactor/autoaccept.sls && exit 0

mkdir -p /srv/reactor/
mv -f /tmp/autoaccept.sls /srv/reactor/autoaccept.sls
systemctl restart eole-workstation-manager.service

exit 0
