#!/bin/bash

timedatectl set-timezone Europe/Madrid

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

## NC<24 => PHP=7.4
## NC>=24 => PHP=8.1 OR PHP=7.4
## NC>=30 => PHP=8.3
## https://www.linuxcapable.com/how-to-install-php-7-4-on-ubuntu-22-04-lts/
PHP_VERSION=8.3

NETWORK_INTERFACE=eth0

PHP_INI=/etc/php/${PHP_VERSION}/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

md5sum -c ${NEXTCLOUD_INSTALLER_ARCHIVE}.md5 < ${NEXTCLOUD_INSTALLER_ARCHIVE}

md5sum_exit_status=$?

cd --

echo "Exit status for md5sum check for Nextcloud installer: ${md5sum_exit_status}"

if [ "${md5sum_exit_status}" == "0" ]; then
    echo "Check OK"
else
    echo "Check KO"
    echo "Aborting"
    exit 1
fi

## Install the needed packages from apt repositories


if [ "${PHP_VERSION}" == "7.4" ]; then

	apt update

	apt install -y software-properties-common apt-transport-https

	add-apt-repository ppa:ondrej/php -y

fi

apt update

apt install -y 	apache2					\
		mariadb-server				\
		libapache2-mod-php${PHP_VERSION} 	\
		imagemagick				\
		bzip2					\
		php${PHP_VERSION}-gd 			\
		php${PHP_VERSION}-mysql			\
		php${PHP_VERSION}-curl 			\
		php${PHP_VERSION}-mbstring 		\
		php${PHP_VERSION}-intl			\
		php${PHP_VERSION}-gmp			\
		php${PHP_VERSION}-bcmath		\
		php${PHP_VERSION}-imagick		\
		php${PHP_VERSION}-xml			\
		php${PHP_VERSION}-zip			\
		redis					\
		php${PHP_VERSION}-redis			\
		mkcert

## For troubleshooting, it is typically useful to be able to access the db server from a graphical UI
sed -i "s|bind-address|#bind-address|g" /etc/mysql/mariadb.conf.d/50-server.cnf

systemctl restart mariadb

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

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

echo "START - Create the database"

mariadb -u root -e 'create database nextcloud_db;'

mariadb -u root -e "create user nextcloud_usr@'%' identified by 'nextcloud_usr'"

mariadb -u root -e "grant all privileges on nextcloud_db.* to 'nextcloud_usr'@'%'"

echo "END - Create the database"


## Expand the installer archive and move the content to the web server root folder (/var/www)

echo "START - Expand the installer archive and move the content to the web server root folder (/var/www)"

cd /vagrant/artifacts

tar -xjf ${NEXTCLOUD_INSTALLER_ARCHIVE}

cp -r nextcloud /var/www

echo "END - Expand the installer archive and move the content to the web server root folder (/var/www)"


## Apache Web Server Configuration

echo "START - Apache Web Server Configuration"

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

## Putting the machine hostname in the Apache site configuration file (nextcloud.conf)
sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /etc/apache2/sites-available/nextcloud.conf

cp /vagrant/artifacts/nc-redirect.conf /etc/apache2/sites-available/nc-redirect.conf

## Putting the machine hostname in the Apache site configuration file (nc-redirect.conf)
sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /etc/apache2/sites-available/nc-redirect.conf

## Use mkcert to install a locally trusted SSL certificate
chown root.ssl-cert  /etc/ssl/private/${MACHINE_HOSTNAME}-key.pem

chmod 640 /etc/ssl/private/${MACHINE_HOSTNAME}-key.pem

## Activate nextcloud.conf
a2ensite nextcloud.conf

## Activate nc-redirect.conf
a2ensite nc-redirect.conf

## Disactivate 000-default.conf
a2dissite 000-default.conf

## For Nextcloud to work correctly, we need the module mod_rewrite. Enable it by running:
a2enmod rewrite

## Additional recommended modules are mod_headers, mod_env, mod_dir and mod_mime:
a2enmod headers

a2enmod env

a2enmod dir

a2enmod mime

a2enmod ssl

chown -R www-data:www-data /var/www/nextcloud/

echo "END - Apache Web Server Configuration"

## Create a local wrapper occ command
cp /vagrant/artifacts/occ /usr/local/bin/occ

chmod +x /usr/local/bin/occ

## Installing Nextcloud from CLI (https://docs.nextcloud.com/server/stable/admin_manual/installation/command_line_installation.html)
echo "START - Installing Nextcloud from CLI"

admin_usr=admin

occ  maintenance:install 	--database       "mysql"\
				--database-name  "nextcloud_db"\
				--database-host  "localhost"\
				--database-user  "nextcloud_usr"\
				--database-pass  "nextcloud_usr"\
				--admin-user 	 "${admin_usr}"\
				--admin-pass 	 "${admin_usr}"

## Adding the Hostname in the trusted_domains config key
occ config:system:set trusted_domains 1 --value "${MACHINE_HOSTNAME}"

echo "END - Installing Nextcloud from CLI"

## Tweaking some Nextcloud settings
echo "START - Tweaking some Nextcloud settings"

## Increasing PHP memory_limit to 512M
sed -i "s|memory_limit =.*|memory_limit = 512M|g" "$PHP_INI"

## Setting up pretty URLs
occ config:system:set htaccess.RewriteBase --value '/'

occ config:system:set overwrite.cli.url --value "https://${MACHINE_HOSTNAME}"

occ maintenance:update:htaccess

## Setting up Redis Cache configuration
usermod -a -G redis www-data

cp /vagrant/artifacts/redis.conf /etc/redis/redis.conf

chown redis.redis /etc/redis/redis.conf

systemctl restart redis


## Order is important here. The 'redis' array must be configured first.
occ config:system:set redis host --value '/var/run/redis/redis-server.sock' 

occ config:system:set redis port --value 0

occ config:system:set redis timeout --value 0.0

occ config:system:set memcache.local   --value '\OC\Memcache\Redis'

occ config:system:set memcache.locking --value '\OC\Memcache\Redis'

occ config:system:set filelocking.enabled --value 'true'

occ config:app:set backgroundjob backgroundjobs_name --value="cron"

occ app:disable recommendations

occ config:app:set text workspace_available --value=0

echo "END - Tweaking some Nextcloud settings"

systemctl restart apache2

systemctl status apache2

## Install crontab for www-data for Nextcloud Background jobs
crontab -u www-data /vagrant/artifacts/crontab-www-data

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 DNS,"

echo "you can connect to this Nextcloud instance with the following URL: https://${MACHINE_HOSTNAME}"

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