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

adduser --disabled-password --gecos GECOS ${SYSTEM_USER}
 
usermod -p "`openssl passwd -1  -salt 5RPVAd ${SYSTEM_USER}`" ${SYSTEM_USER}
 
adduser ${SYSTEM_USER} sudo

dpkg -i /vagrant/artifacts/${ZABBIX_DEB_PACKAGE}

apt update

apt install -y zabbix-server-pgsql \
	zabbix-frontend-php \
	php8.1-pgsql \
	zabbix-apache-conf \
	zabbix-sql-scripts \
	zabbix-agent \
	postgresql \
	mkcert
	
cp /vagrant/artifacts/pg_hba.conf /etc/postgresql/14/main/

systemctl restart postgresql

cp 	/vagrant/artifacts/zabbix_server.conf /etc/zabbix/

sudo -u postgres psql -c "CREATE USER zabbix_usr WITH PASSWORD 'zabbix_usr';"

zcat /usr/share/zabbix-sql-scripts/postgresql/server.sql.gz > /tmp/zabbix_db_ddl.sql

sudo -u postgres createdb -O zabbix_usr zabbix_db;

PGPASSWORD=zabbix_usr psql -f /tmp/zabbix_db_ddl.sql -h 127.0.0.1 -U zabbix_usr -d zabbix_db

systemctl restart zabbix-server zabbix-agent apache2

systemctl enable zabbix-server zabbix-agent apache2

cp /vagrant/artifacts/zabbix.conf.php  /etc/zabbix/web/

chown www-data.www-data /etc/zabbix/web/zabbix.conf.php

systemctl restart zabbix-server

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}"

cp 	/vagrant/artifacts/zabbix_virtualhost.conf  /etc/apache2/sites-available/

sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /etc/apache2/sites-available/zabbix_virtualhost.conf 

a2enmod ssl

systemctl restart apache2

a2ensite zabbix_virtualhost.conf 

a2dissite 000-default.conf

systemctl reload apache2

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 or configure LXD nameserver,"

echo "you can start configuring and using your Zabbix instance by connecting to the web panel https://${MACHINE_HOSTNAME} with user Admin and password zabbix"

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