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

## Copy the notify_push binary in its dedicated folder
mkdir /opt/notify_push

cp /vagrant/artifacts/notify_push /opt/notify_push/

chmod +x /opt/notify_push/notify_push

## Create the environment file for the notify_push systemd service
mkdir /etc/notify_push

cp /vagrant/artifacts/notify_push.env /etc/notify_push/

sed -i "s|#NEXTCLOUD_URL#|${NEXTCLOUD_URL}|g" /etc/notify_push/notify_push.env

sed -i "s|#DATABASE_URL#|${DATABASE_URL}|g" /etc/notify_push/notify_push.env

sed -i "s|#REDIS_URL#|${REDIS_URL}|g" /etc/notify_push/notify_push.env

sed -i "s|#PORT#|${PORT}|g" /etc/notify_push/notify_push.env

sed -i "s|#ALLOW_SELF_SIGNED#|${ALLOW_SELF_SIGNED}|g" /etc/notify_push/notify_push.env

sed -i "s|#DATABASE_PREFIX#|${DATABASE_PREFIX}|g" /etc/notify_push/notify_push.env

## Create, enable and start the systemd service
cp /vagrant/artifacts/notify_push.service /etc/systemd/system/ 

systemctl daemon-reload

systemctl enable notify_push

systemctl start notify_push

systemctl status notify_push

end_time=`date`

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

echo "The notify_push service is listening on port ${PORT} to proxy notifications from ${NEXTCLOUD_URL}"

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