#!/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}'`

## Install Haproxy - latest version: https://www.haproxy.com/blog/how-to-install-haproxy-on-ubuntu/
apt update

apt install  -y --no-install-recommends software-properties-common gnupg-agent

add-apt-repository -y ppa:vbernat/haproxy-2.7

apt update

apt-cache policy haproxy

apt install -y haproxy

## Install the mkcert rootCA (see https://github.com/FiloSottile/mkcert#installing-the-ca-on-other-systems) 
apt install mkcert

export CAROOT=/vagrant/artifacts/

mkcert -install

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

## HAproxy needs the certificate and the key in the same file
cat /etc/ssl/certs/${MACHINE_HOSTNAME}.pem /etc/ssl/private/${MACHINE_HOSTNAME}-key.pem > /etc/ssl/private/${MACHINE_HOSTNAME}-full.pem

## Replace the HAproxy configuration file
cp /vagrant/artifacts/haproxy.cfg /etc/haproxy/haproxy.cfg

sed -i "s|#WEBSERVER_NODE01_HOSTNAME#|${WEBSERVER_NODE01_HOSTNAME}|g" /etc/haproxy/haproxy.cfg

sed -i "s|#WEBSERVER_NODE02_HOSTNAME#|${WEBSERVER_NODE02_HOSTNAME}|g" /etc/haproxy/haproxy.cfg

systemctl status haproxy

systemctl start haproxy

end_time=`date`

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

echo "provisioning started: ${start_time}" 
 
echo "provisioning ended: ${end_time}"
