#!/bin/bash


TMP_DIR=$(mktemp -dq)
BOOTSTRAP_PATH=$TMP_DIR/bootstrap.ldif
cp /opt/rudder/share/bootstrap.ldif $BOOTSTRAP_PATH

INITPOLICY_PATH=$TMP_DIR/init-policy-server.ldif
cp /opt/rudder/share/init-policy-server.ldif $INITPOLICY_PATH


then
  RUDDER_HOSTNAME=$(hostname -f)
else
  RUDDER_HOSTNAME=$(hostname)
fi


  # we need to insert a double baclslask (\\n) because it vill be reinterpreted by the sed below
  CERTIFICATE=$(perl -pe 's/\n/\\\\n/' /opt/rudder/etc/ssl/agent.cert)

  sed -i "s/^\([^#].*\)%%POLICY_SERVER_HOSTNAME%%/\1${RUDDER_HOSTNAME}/g" $INITPOLICY_PATH
  sed -i "s#^\([^#].*\)%%POLICY_SERVER_ALLOWED_NETWORKS%%#\1$#g" $INITPOLICY_PATH
  sed -i "s#^\([^#].*\)%%POLICY_SERVER_CERTIFICATE%%#\1${CERTIFICATE}#g" $INITPOLICY_PATH
  


RUDDER_OPT="/opt/rudder"
LDAP_CREDENTIALS=$(grep -c -E "^ldap.auth(dn|pw)[ \t]*=" /opt/rudder/etc/rudder-web.properties || true)

if [ -f /opt/rudder/etc/rudder-web.properties -a ${LDAP_CREDENTIALS} -eq 2 ]; then
  # Get the database access credentials from the rudder-web.properties file
  LDAP_USER="$(grep -E '^ldap.authdn[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d "=" -f 2-)"
  LDAP_PASSWORD="$(grep -E '^ldap.authpw[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d "=" -f 2-)"
else
  # No database access credentials in rudder-web.properties... Try anyway using "guessed" values.
  echo "WARNING: Database access credentials are missing in /opt/rudder/etc/rudder-web.properties, trying to guess adequate values."
  LDAP_USER=$(grep "^rootdn" /opt/rudder/etc/openldap/slapd.conf | sed "s/\w*\s*['\"]\?\([^\"']*\)['\"]\?$/\1/")
  LDAP_PASSWORD=$(grep "^rootpw" /opt/rudder/etc/openldap/slapd.conf | sed "s/\w*\s*['\"]\?\([^\"']*\)['\"]\?$/\1/")
fi

# Commands
LDAP_PARAMETERS="-H ldap://localhost/ -D ${LDAP_USER} -w ${LDAP_PASSWORD} -x"


LDAPADD="ldapadd ${LDAP_PARAMETERS}"

${LDAPADD} -c -f $BOOTSTRAP_PATH
${LDAPADD} -c -f $INITPOLICY_PATH

