#!/bin/bash

timedatectl set-timezone Europe/Madrid

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

MINIO_STORAGE_FOLDER=/usr/local/share/minio/

MINIO_ADMIN=admin

MINIO_ADMIN_PASSWORD=admin123

MINIO_NEXTCLOUD_USER=nextcloud_usr

MINIO_NEXTCLOUD_PASSWORD=nextcloud_usr


NETWORK_INTERFACE=eth0

hostnamectl set-hostname ${MACHINE_HOSTNAME}

# Print some information about the container OS
hostnamectl

# Print some information about the container timezone
timedatectl

#####################################################################
## Script inspired by https://www.digitalocean.com/community/tutorials/how-to-set-up-an-object-storage-server-using-minio-on-ubuntu-18-04
#####################################################################
cp /vagrant/artifacts/minio /usr/local/bin

cp /vagrant/artifacts/mc /usr/local/bin

chmod +x /usr/local/bin/minio

mkdir /etc/minio

cp /vagrant/artifacts/minio.conf /etc/minio

sed -i "s|#MACHINE_HOSTNAME#|${MACHINE_HOSTNAME}|g" /etc/minio/minio.conf 

sed -i "s|#MINIO_STORAGE_FOLDER#|${MINIO_STORAGE_FOLDER}|g" /etc/minio/minio.conf 

cp /vagrant/artifacts/minio.service /etc/systemd/system/

mkdir ${MINIO_STORAGE_FOLDER}

export CAROOT=/vagrant/artifacts/

apt install mkcert
 
mkcert -install

mkdir /etc/minio/certs
 
mkcert  --cert-file /etc/minio/certs/public.crt --key-file /etc/minio/certs/private.key "${MACHINE_HOSTNAME}"

systemctl daemon-reload

systemctl enable minio

systemctl start minio

systemctl status minio

## Add a user for Nextcloud
sleep 10

mc alias remove local

mc alias set local https://${MACHINE_HOSTNAME}:9000 ${MINIO_ADMIN} ${MINIO_ADMIN_PASSWORD}

mc admin user add local ${MINIO_NEXTCLOUD_USER} ${MINIO_NEXTCLOUD_PASSWORD}

mc admin policy attach local readwrite --user ${MINIO_NEXTCLOUD_USER}

end_time=`date`

echo "You can connect with user '${MINIO_ADMIN}' (password: '${MINIO_ADMIN_PASSWORD}') to the MinIO Web Console https://${MACHINE_HOSTNAME}:9000" 

echo "The user created for Nextcloud is nextcloud_usr (password: 'nextcloud_usr')"

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