#!/bin/bash

timedatectl set-timezone Europe/Madrid

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

#PHP_INI=/etc/php/7.4/apache2/php.ini

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

## Install Nextcloud: https://docs.nextcloud.com/server/stable/admin_manual/installation/example_ubuntu.html

#####
## Step 001
## Check the MD5 of the Nextcloud Installer 


##(cd to the folder to avoid a 'File Not Found' error
cd /vagrant/artifacts

## Install the needed packages from apt repositories
apt update

apt install -y mariadb-server

## Replace the MariaDB configuration file and restart MariaDB
cp /vagrant/artifacts/50-server.cnf /etc/mysql/mariadb.conf.d/50-server.cnf

systemctl restart mysql

## Create the database and the user for the Nextcloud backend database

echo "START - Create the database"

mysql -u root -e "create database ${NEXTCLOUD_DB_NAME};"

mysql -u root -e 'create user "'"${NEXTCLOUD_DB_USER}"'" identified by "'"${NEXTCLOUD_DB_PASSWORD}"'"' 

mysql -u root -e "grant all privileges on ${NEXTCLOUD_DB_NAME}.* to ${NEXTCLOUD_DB_USER}@'%'"

echo "END - Create the database"

echo "START - Cleanup"

rm -rf /vagrant/artifacts/nextcloud

echo "END - Cleanup"

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 connect to this MariaDB instance on standard port 3306 with the following parameters:"

echo " 		hostname: ${MACHINE_HOSTNAME}"

echo " 		database name: ${NEXTCLOUD_DB_NAME}"

echo "		username: ${NEXTCLOUD_DB_USER}"

echo "		password: ${NEXTCLOUD_DB_PASSWORD}"

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