#!/bin/bash
timedatectl set-timezone Europe/Madrid
start_time=`date`
echo "provisioning started: ${start_time}"
#### The user must fill these variables - START
# Fully Qualified Name
MACHINE_HOSTNAME=
# Hostname of the first node of the webserver farm
WEBSERVER_NODE01_HOSTNAME=
# Hostname of the first node of the webserver farm
WEBSERVER_NODE02_HOSTNAME=
#### The user must fill these variables - END
SYSTEM_USER=usrv
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}'`
adduser --disabled-password --gecos GECOS ${SYSTEM_USER}
usermod -p "`openssl passwd -1 -salt 5RPVAd ${SYSTEM_USER}`" ${SYSTEM_USER}
adduser ${SYSTEM_USER} sudo
## Install Haproxy - latest version: https://www.haproxy.com/blog/how-to-install-haproxy-on-ubuntu/
apt install -y --no-install-recommends software-properties-common
add-apt-repository -y ppa:vbernat/haproxy-2.4
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)
chmod u+x /vagrant/artifacts/mkcert
export CAROOT=/vagrant/artifacts/
/vagrant/artifacts/mkcert -install
/vagrant/artifacts/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 "If you add this IP to the hostname (${MACHINE_HOSTNAME}) in your hosts file:"
echo " You can connect with user ${SYSTEM_USER} via ssh (password ${SYSTEM_USER}): ssh ${SYSTEM_USER}@${MACHINE_HOSTNAME}"
echo "provisioning started: ${start_time}"
echo "provisioning ended: ${end_time}"