#!/bin/bash

timedatectl set-timezone Europe/Madrid

start_time=`date`
  
echo "provisioning started: ${start_time}" 

NETWORK_INTERFACE=eth0

hostnamectl set-hostname ${MACHINE_HOSTNAME}

# Print some information about the container OS
hostnamectl

# Print some information about the container timezone
timedatectl

#####################################################################
## Get the IP address into an environment variable. This command outputs 
## an empty variable if the network interface name is not ${NETWORK_INTERFACE}
#####################################################################
ip_address=`ip -4 addr show ${NETWORK_INTERFACE} | grep -oP '(?<=inet\s)\d+(\.\d+){3}'`

export DEBIAN_FRONTEND=noninteractive

apt update

# Quiet installation of OpenLDAP server
# https://apassionatechie.wordpress.com/2017/12/12/automating-slapd-install/

cat /vagrant/artifacts/debconf-slapd.conf | debconf-set-selections

apt install 	ldap-utils \
		slapd   \
	 	apache2 \
		ldap-account-manager \
		-y

export CAROOT=/vagrant/artifacts/

apt install mkcert -y

mkcert -install

mkcert  --cert-file /etc/ssl/certs/${MACHINE_HOSTNAME}.pem --key-file /etc/ssl/private/${MACHINE_HOSTNAME}-key.pem "${MACHINE_HOSTNAME}"

a2enmod ssl

cp /vagrant/artifacts/ldap-account-manager.conf /etc/apache2/sites-available/

sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /etc/apache2/sites-available/ldap-account-manager.conf

cp /vagrant/artifacts/lam.conf /var/lib/ldap-account-manager/config/lam.conf

a2ensite ldap-account-manager.conf

a2dissite 000-default.conf

systemctl restart apache2

end_time=`date`

echo "This container has IP (interface: ${NETWORK_INTERFACE}): ${ip_address}"

echo "If you add this IP to the hostname (${MACHINE_HOSTNAME}) in your hosts file or configure LXD nameserver,"

echo "Your LDAP instance can be managed with LDAP Account Manager, accessible via the following URL: https://${MACHINE_HOSTNAME}/lam"

echo "with user 'lam' and password 'lam'"

echo "provisioning started: ${start_time}" 

echo "provisioning ended: ${end_time}"
