#!/bin/bash

set -e

PROGNAME=$(basename "$0")
BOOTSTRAPPED=0
AAPI_RELOAD=0
AUTO_CONFIG='false'

. /usr/share/grommunio-pkg-bits/scripts/setup-include.sh
SHARED_TEMPLATES='
shared/grommunio/site-fqdn
shared/grommunio/site-domain
shared/grommunio-files/endpoint-url
shared/grommunio-office/endpoint-url
shared/grommunio-files/config-office-force
shared/grommunio/auto-config
shared/grommunio/admin-password
shared/grommunio/admin-password-again
shared/grommunio/admin-password-mismatch
shared/grommunio/admin-password-must-enter
'
PKG_TEMPLATES='
grommunio-files/internal/db-purge
'

configure_files () {
	# Detect if Keycloak already set up
        db_get grommunio-files/db/dbname || true
        local TEST_DB_NAME="$RET"
        if [ -n "$TEST_DB_NAME" ]; then
                [ -f "/etc/dbconfig-common/grommunio-files.conf" ] && BOOTSTRAPPED=1
        fi

	# Create and intialise DB
	. /usr/share/dbconfig-common/dpkg/postinst.mysql
	# you can overwrite the default database encoding, LC_COLLATE and LC_CTYPE
	dbc_mysql_createdb_encoding="UTF8"
	dbc_sql_substitutions="yes"
	dbc_go grommunio-files "$@"

	# Source db config
	local SOURCED_DB_CONFIG=0
	if [ -r /etc/dbconfig-common/grommunio-files.conf ]; then
		. /etc/dbconfig-common/grommunio-files.conf && SOURCED_DB_CONFIG=1

		# Fix purge flag - this is created by dbconfig-mysql
		local DB_PURGE=''
		if db_get grommunio-files/internal/db-purge; then
			DB_PURGE="$RET"
		fi
		[ -z "$DB_PURGE" ] && DB_PURGE="true"
		db_set grommunio-files/purge "$DB_PURGE"
	fi

	# g-files config.php
	ENDPOINT_URL='localhost'
	FQDN=''
	BASE_PATH=''
	db_get shared/grommunio/site-fqdn
	[ -n "$RET" ] && ENDPOINT_URL="$RET"
	[ -n "$RET" ] && OFFICE_ENDPOINT_URL="$RET"
	db_get shared/grommunio-files/endpoint-url
	[ -n "$RET" ] && ENDPOINT_URL="$RET"
	if echo "$ENDPOINT_URL" | grep -qP '^[^/]+$'; then
		ENDPOINT_URL="https://${ENDPOINT_URL}/files"
	fi
	BASE_PATH=$(trurl "$ENDPOINT_URL" --get '{path}')
	[ "$BASE_PATH" = '/' ] && BASE_PATH=''
	FQDN=$(trurl "$ENDPOINT_URL" --get '{host}')

	db_get shared/grommunio-office/endpoint-url
	[ -n "$RET" ] && OFFICE_ENDPOINT_URL="$RET"
	if echo "$OFFICE_ENDPOINT_URL" | grep -qP '^[^/]+$'; then
		OFFICE_ENDPOINT_URL="https://${OFFICE_ENDPOINT_URL}/office"
	fi
	OFFICE_BASE_PATH=$(trurl "$OFFICE_ENDPOINT_URL" --get '{path}')
	[ "$OFFICE_BASE_PATH" = '/' ] && OFFICE_BASE_PATH=''

	CONFIG_OFFICE_FORCE='false'
	db_get shared/grommunio-files/config-office-force
	[ -n "$RET" ] && CONFIG_OFFICE_FORCE="$RET"

	local DOMAIN=''
	db_get shared/grommunio/site-domain
	[ -n "$RET" ] && DOMAIN="$RET"
	ADMIN_PASSWORD=''
	db_get shared/grommunio/admin-password
	[ -n "$RET" ] && ADMIN_PASSWORD="$RET"
	DB_TYPE='mysql'
	DB_HOST='localhost'
	DB_PORT='3306'
	DB_NAME='grofiles'
	DB_USER='grofiles'
	DB_PASSWORD='KnockKnock'
        if [ $SOURCED_DB_CONFIG -eq 1 ]; then
                [ "$dbc_dbtype" = 'mysql' ] && DB_TYPE='mysql'
                [ "$dbc_dbtype" = 'pgsql' ] && DB_TYPE='pgsql'
                DB_HOST="$dbc_dbserver"
                DB_PORT="$dbc_dbport"
                DB_NAME="$dbc_dbname"
                DB_USER="$dbc_dbuser"
                DB_PASSWORD="$dbc_dbpass"
        fi

	# Initialize config.php if it does not exist yet
	local CFG_FILE=/var/lib/grommunio-files/config/config.php
	if ! [ -e "$CFG_FILE" ]; then
		cp /usr/share/grommunio-files/config-templates/config.php "$CFG_FILE"
		chown grofiles:grofiles "$CFG_FILE"
		chmod 640 "$CFG_FILE"
	fi

	return 0
}

pre_start_files () {
	local DISTRO_FAMILY=$(get_distro_family)
	local YE_OLDE_PWD=$(pwd)
	cd /usr/share/grommunio-files
		if [ "$AUTO_CONFIG" = 'true' -a $BOOTSTRAPPED -eq 0 ]; then
			rm -rf data/admin 2>/dev/null || true
			sudo -u grofiles ./occ -q -n maintenance:install --database="$DB_TYPE" --database-name="${DB_NAME}" --database-user="${DB_USER}" --database-pass="${DB_PASSWORD}" --admin-user=admin --admin-pass="${ADMIN_PASSWORD}" --data-dir=/var/lib/grommunio-files/data
		fi
                sudo -u grofiles ./occ -q -n config:system:set trusted_domains 1 --value="${FQDN}"
		sudo -u grofiles ./occ -q -n config:system:set trusted_domains 2 --value="${DOMAIN}"
		sudo -u grofiles ./occ -q -n config:system:set trusted_domains 3 --value="mail.${DOMAIN}"
		sudo -u grofiles ./occ config:system:set overwritewebroot --value="$BASE_PATH"
		#sudo -u grofiles ./occ config:system:set overwrite.cli.url --value="https://${FQDN}"
		sudo -u grofiles ./occ -q -n app:enable user_external
		sudo -u grofiles ./occ -q -n config:system:set user_backends 0 arguments 0 --value="https://${FQDN}/dav"
		sudo -u grofiles ./occ -q -n config:system:set user_backends 0 class --value='\OCA\UserExternal\BasicAuth'
		sudo -u grofiles ./occ -q -n app:enable onlyoffice
		sudo -u grofiles ./occ -q -n config:system:set integrity.check.disabled --type boolean --value true
		sudo -u grofiles ./occ -q -n theming:config name 'grommunio Files'
		sudo -u grofiles ./occ -q -n theming:config logo /usr/share/grommunio-files/logo.svg
		sudo -u grofiles ./occ -q -n theming:config logoheader /usr/share/grommunio-files/logo.svg
		#sudo -u grofiles ./occ -q -n theming:config favicon /usr/share/grommunio-files/favicon.svg
		sudo -u grofiles ./occ -q -n theming:config background /usr/share/grommunio-files/background.jpg
		sudo -u grofiles ./occ -q -n theming:config -r disable-user-theming
		sudo -u grofiles ./occ -q -n theming:config slogan 'filesync & sharing'
		sudo -u grofiles ./occ -q -n theming:config url 'https://grommunio.com'
		sudo -u grofiles ./occ -q -n theming:config color '#0072B0'
		sudo -u grofiles ./occ -q -n config:system:set mail_from_address --value='admin'
		sudo -u grofiles ./occ -q -n config:system:set mail_smtpmode --value='sendmail'
		sudo -u grofiles ./occ -q -n config:system:set mail_sendmailmode --value='smtp'
		sudo -u grofiles ./occ -q -n config:system:set mail_domain --value="${DOMAIN}"
		sudo -u grofiles ./occ -q -n config:system:set mail_smtphost --value='localhost'
		sudo -u grofiles ./occ -q -n config:system:set mail_smtpport --value='25'
		sudo -u grofiles ./occ -q -n config:system:set maintenance_window_start --type=integer --value=1
		sudo -u grofiles ./occ -q -n config:system:set check_for_working_wellknown_setup --type=integer --value=0
		# Allow grommunio-keycloak to work on local system
		sudo -u grofiles ./occ -q -n config:system:set allow_local_remote_servers --type=boolean --value=true
		sudo -u grofiles ./occ -q -n app:enable user_oidc
		# Fix Nextcloud openSuse Leap bug not finding system certificates
		case "$DISTRO_FAMILY" in
			suse)
				sudo -u grofiles ./occ -q -n config:system:set default_certificates_bundle_path --type string --value "/var/lib/ca-certificates/ca-bundle.pem"
				;;
			*)
				;;
		esac
	cd "$YE_OLDE_PWD"

	# Always restart php-fpm 
	FILES_RELOAD=1
}

post_start_files () {
	[ $BOOTSTRAPPED -ne 0 ] && return 0
	[ $AUTO_CONFIG != 'true' ] && return 0
#	# wait for the grommunio-chat unix socket, sometimes a second restart required for bind (db population)
#	if ! [ -e "/var/tmp/grommunio-chat_local.socket" ] ; then
#		for n in $(seq 1 30) ; do
#			if [ -e "/var/tmp/grommunio-chat_local.socket" ] ; then
#				echo "chat socket /var/tmp/grommunio-chat_local.socket appeared after $((n*3)) seconds."
#				break
#			fi
#			if [ $n -eq 10 ]; then
#				systemctl restart grommunio-chat
#			fi
#			sleep 3
#		done
#	fi
#	export MMCTL_LOCAL_SOCKET_PATH=/var/tmp/grommunio-chat_local.socket
#	if [ -n "$API_ADMIN_PASSWORD" ]; then
#		if ! /usr/sbin/grommunio-chat-ctl --local user list 2>/dev/null | grep -q ': api\.admin '; then
#			/usr/sbin/grommunio-chat-ctl --local user create --email api.admin@localhost --username api.admin --password "${API_ADMIN_PASSWORD}" --system-admin
#		else
#			echo "User api.admin already exists" 1>&2
#		fi
#	fi
#	if [ -n "$ADMIN_PASSWORD" ]; then
#		if ! /usr/sbin/grommunio-chat-ctl --local user list 2>/dev/null | grep -q ': admin '; then
#			/usr/sbin/grommunio-chat-ctl --local user create --email admin@localhost --username admin --password "${ADMIN_PASSWORD}" --system-admin
#		else
#			echo "User admin already exists" 1>&2
#		fi
#	fi
	if pkg_installed gromunio-office || [ "$CONFIG_OFFICE_FORCE" = 'true' ]; then
		. /usr/share/grommunio-pkg-bits/scripts/grommunio-files-wire-files-office.sh
		wire_files_office "${ENDPOINT_URL}" "${OFFICE_ENDPOINT_URL}"
	fi
	return 0
}

case "$PROGNAME" in
	setup-grommunio-files)
		check_if_root
		start_debconf -x 'grommunio-files' -y 'grommunio-files' "$@"
		configure_files $ARGS
		pre_start_files
		if test "$AUTO_CONFIG" = 'true'; then
			# Make sure nginx picks up on new config
			systemctl try-reload-or-restart nginx.service || true
			systemctl enable php-fpm.service || true
			systemctl try-restart php-fpm.service || true
		else
			STATUS=$(systemctl is-active php-fpm.service || true)
			systemctl try-restart php-fpm.service || true
		fi
		post_start_files
		if test "$AUTO_CONFIG" != 'true'; then
			test "$STATUS" != 'active' && systemctl try-restart php-fpm.service || true
		fi
		;;
	clean-files-db|clean-grommunio-files-db)
		check_if_root
		clean_dbconfig_db -x 'grommunio-files' -y 'grommunio-files'
		;;
esac
