#!/bin/bash

if [ $# -ne 3 ]
then
	echo "$0 <DOMAIN> <IP> <ADMIN_PASSWORD>"
	echo "(Re-)Configure Libre Workspace and m23 for working together"
	exit 23
fi

# Main domain where the Libre Workspace runs on
DOMAIN="$1"

# IP address of Libre Workspace
IP="$2"

# Password of the Libre Workspace administrator
ADMIN_PASSWORD="$3"



# Make the domain resolvable on the server

	# Remove a (maybe) existing DNS entry
	sed -i "/^$IP m23\.$DOMAIN/d" /etc/hosts

	# Add the DNS entry
	echo "$IP m23.$DOMAIN" >> /etc/hosts



# Configure Caddy as reverse proxy for m23

	# Remove a (maybe) existing Caddy entry
	sed -i '/^###m23begin/,/^###m23end/d' /etc/caddy/Caddyfile
	
	# Add the Caddy entry
	echo "###m23begin
m23.$DOMAIN {
    #tls internal
    reverse_proxy localhost:2380
}
###m23end
" >> /etc/caddy/Caddyfile

	# If domain is "int.de" uncomment the tls internal line for internal https
	if [ "$DOMAIN" = "int.de" ]; then
		sed -i 's/#tls internal/tls internal/g' /etc/caddy/Caddyfile
	fi

	# Apply the settings
	systemctl restart caddy



# Overwrite the detection of the m23 server's IP by the domain name
	echo -n "m23.$DOMAIN" > /m23/etc/address.override

# Save the "original" server IP for later use
	echo -n "$IP" > /m23/etc/ip.override

# Get the broadcast address for the IP
	LC_ALL=C /sbin/ifconfig | grep broadcast | grep "$IP" | sed 's/.*broadcast //' | sed 's/[^0-9.]//g' > /m23/etc/broadcast.override

# Get the netmask address for the IP
	LC_ALL=C /sbin/ifconfig | grep netmask | grep "$IP" | sed -e 's/.*netmask //' -e 's/ .*//' > /m23/etc/netmask.override



# Allow access to Samba's DNS
	ufw allow 53



# Create the Administrator account same as in Libre Workspace
	if [ $(/m23/bin/m23cli.php listm23Admins | grep Administrator -c) -eq 0 ]
	then
		/m23/bin/m23cli.php addm23Admin Administrator "$ADMIN_PASSWORD"
	fi



# Remove the default god account, if Administrator account is present
	if [ $(/m23/bin/m23cli.php listm23Admins | grep Administrator -c) -gt 0 ] && [ $(/m23/bin/m23cli.php listm23Admins | grep god -c) -gt 0 ]
	then
		/m23/bin/m23cli.php delm23Admin god
	fi