#!/bin/bash

timedatectl set-timezone Europe/Madrid

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

hostnamectl set-hostname ${MACHINE_HOSTNAME}

# Print some information about the container OS
hostnamectl

# Print some information about the container timezone
timedatectl

ADMIN_PASSWORD=admin123

#####################################################################
## Get the IP address into an environment variable.
#####################################################################
ip_address_list=`hostname -I`

ip_address_list=($ip_address_list)

ip_address_0=${ip_address_list[0]}

echo "ip_address_0=${ip_address_0}"

apt update

apt install -y 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}"

useradd -m -d /home/mox mox

mkdir /home/mox/config

cp /vagrant/artifacts/mox.conf /home/mox/config

sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /home/mox/config/mox.conf

sed -i "s|#ip_address_0#|${ip_address_0}|g" /home/mox/config/mox.conf

cp /vagrant/artifacts/domains.conf /home/mox/config

sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /home/mox/config/domains.conf

sed -i "s|#MAIL_DOMAIN#|${MAIL_DOMAIN}|g" /home/mox/config/domains.conf


mkdir /home/mox/data

cp /vagrant/artifacts/mox /home/mox/

cd /home/mox/

echo ${ADMIN_PASSWORD} | /home/mox/mox setadminpassword

chown -R mox.mox /home/mox

systemctl enable /vagrant/artifacts/mox.service

echo "${ip_address_0} ${MAIL_DOMAIN}" >> /etc/hosts

systemctl start mox.service

end_time=`date`

echo "This container has the following IP address: ${ip_address_0}"

echo "The web admin panel can be accessed with user admin@${MAIL_DOMAIN} and password ${ADMIN_PASSWORD}"

echo "at the following link: https://${MACHINE_HOSTNAME}:444/admin/"

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