#!/bin/bash

# Disable ssl
coolconfig set ssl.enable  false
coolconfig set ssl.termination  true
coolconfig set net.listen loopback
coolconfig set net.proto IPv4


#Generate a list of hosts that can access to the wopi storage
#Server FQDN
AllowWopiHosts=`hostname`
NCdomains=$(perl -Mesmith::DomainsDB -e 'my $domains = esmith::DomainsDB->open; my @DOM = $domains->get_all_by_prop(TemplatePath=>"NextcloudVirtualHost"); print( join("|" , map { $_->key } @DOM)) ')
COdomains=$(perl -Mesmith::DomainsDB -e 'my $domains = esmith::DomainsDB->open; my @DOM = $domains->get_all_by_prop(TemplatePath=>"Collabora"); print( join("|" , map { $_->key } @DOM)) ')
if [[ -n $NCdomains ]] ;then AllowWopiHosts+="|$NCdomains";fi
if [[ -n $COdomains ]] ;then AllowWopiHosts+="|$COdomains";fi

#Additional external host 
if [[ -n `/sbin/e-smith/config getprop coolwsd AllowWopiHost` ]];then AllowWopiHosts+="|`/sbin/e-smith/config getprop coolwsd AllowWopiHost |sed -e 's/,/|/g' `";fi

coolconfig set storage.wopi.host "$AllowWopiHosts"


if [[ -n `/sbin/e-smith/config getprop coolwsd VirtualHost` ]]; then

  #Configure smeserver-Nextcloud
  if [[ -x "/usr/bin/occ" ]]; then

    /usr/bin/occ app:install richdocuments

    /usr/bin/occ config:app:set richdocuments wopi_url --value=https://`echo $COdomains|cut -d'|' -f1`

    /usr/bin/occ app:enable richdocuments

    /usr/bin/occ config:system:set allow_local_remote_servers --value true --type bool
    
    /usr/bin/occ config:app:get richdocuments wopi_allowlist || /usr/bin/occ config:app:set richdocuments wopi_allowlist --value `/usr/sbin/e-smith/config get LocalIP`
  fi

fi
