#!/bin/bash

timedatectl set-timezone Europe/Madrid

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

OS_VERSION=ubuntu2204

COLLABORA_USER=usrv

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

## How-To: Setting up and configuring native CODE packages on Linux
## https://www.collaboraoffice.com/code/linux-packages/

apt update

apt install -y gnupg wget ca-certificates mkcert

wget -O /usr/share/keyrings/collaboraonline-release-keyring.gpg  https://collaboraoffice.com/downloads/gpg/collaboraonline-release-keyring.gpg


if [ "${CUSTOMER_HASH}" == "" ]; then
    APT_REPOSITORY_URL=https://www.collaboraoffice.com/repos/CollaboraOnline/CODE-${OS_VERSION}
else
    APT_REPOSITORY_URL=https://www.collaboraoffice.com/repos/CollaboraOnline/${CO_VERSION}/customer-${OS_VERSION}-${CUSTOMER_HASH}
fi

cp /vagrant/artifacts/collaboraonline.sources /etc/apt/sources.list.d/

## Changing the APT Repository URL in the APT source file 
sed -i "s|#APT_REPOSITORY_URL#|${APT_REPOSITORY_URL}|g" /etc/apt/sources.list.d/collaboraonline.sources

apt update

if [ "${CUSTOMER_HASH}" == "" ]; then
   apt install -y coolwsd code-brand
else
   apt install -y coolwsd collabora-online-brand nextcloud-office-brand
fi

export CAROOT=/vagrant/artifacts/

mkcert -install

mkcert  --cert-file /etc/coolwsd/fullchain.pem --key-file /etc/coolwsd/privatekey.pem "${MACHINE_HOSTNAME}"

chown cool:cool  /etc/coolwsd/fullchain.pem /etc/coolwsd/privatekey.pem

## Install the provisioned configuration file for the Collabora Server (coolwsd.xml)
cp /vagrant/artifacts/coolwsd.xml  /etc/coolwsd/

## Install the provisioned systemd service file (coolwsd.service)
cp /vagrant/artifacts/coolwsd.service /lib/systemd/system/coolwsd.service

## The Collabora executable must be given the capability to bind to port 443, HTTPS standard port
setcap CAP_NET_BIND_SERVICE=+eip /usr/bin/coolwsd

systemctl daemon-reload

systemctl restart coolwsd

systemctl status coolwsd

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

echo "your Collabora Server instance is  accessible via the following URL: https://${MACHINE_HOSTNAME}"

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