#!/bin/bash

timedatectl set-timezone Europe/Madrid

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

KEYCLOAK_INSTALLER_VERSION=keycloak-${KEYCLOAK_VERSION}

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}'`

apt update
 
apt install -y default-jdk mkcert

tar -xf /vagrant/artifacts/${KEYCLOAK_INSTALLER_VERSION}.tar.gz

mv ${KEYCLOAK_INSTALLER_VERSION} /opt
 
ln -s /opt/${KEYCLOAK_INSTALLER_VERSION}  /opt/keycloak
 
mkdir /etc/keycloak

cp /vagrant/artifacts/keycloak-env.conf /etc/keycloak/keycloak-env.conf

cp /vagrant/artifacts/keycloak.service /etc/systemd/system/keycloak.service

sed -i "s|#KEYCLOAK_USER#|${KEYCLOAK_USER}|g" /etc/systemd/system/keycloak.service

cp /vagrant/artifacts/keycloak.conf /opt/keycloak/conf/keycloak.conf

sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /opt/keycloak/conf/keycloak.conf

export CAROOT=/vagrant/artifacts/

mkcert -install

mkcert  --cert-file /opt/keycloak/conf/server-crt.pem --key-file /opt/keycloak/conf/server-key.pem "${MACHINE_HOSTNAME}"


systemctl daemon-reload
 
systemctl enable keycloak

systemctl start keycloak

systemctl status keycloak

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 "	Your Keycloak Server instance is  accessible via the following URL: https://${MACHINE_HOSTNAME}:8443"

echo " 	The admin panel is accessible with user 'admin' and password 'admin'"

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