#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source /usr/share/yunohost/helpers

# Stop script if errors
ynh_abort_if_errors

# Import common cmd
source ../settings/scripts/psql.sh
source ../settings/scripts/experimental_helper.sh
source ../settings/scripts/_common.sh

#=================================================
# SET ALL CONSTANT
#=================================================

app=$YNH_APP_INSTANCE_NAME
synapse_user="matrix-$app"
synapse_db_name="matrix_$app"
synapse_db_user="matrix_$app"
upstream_version=$(ynh_app_upstream_version)

#=================================================
# LOAD SETTINGS
#=================================================

domain=$(ynh_app_setting_get $app special_domain)
path_url=$(ynh_app_setting_get $app special_path)
final_path=$(ynh_app_setting_get $app final_path)
synapse_db_pwd=$(ynh_app_setting_get $app synapse_db_pwd)
synapse_tls_port=$(ynh_app_setting_get $app synapse_tls_port)
turnserver_tls_port=$(ynh_app_setting_get $app turnserver_tls_port)
turnserver_alt_tls_port=$(ynh_app_setting_get $app turnserver_alt_tls_port)

#=================================================
# CHECK IF THE APP CAN BE RESTORED
#=================================================

ynh_webpath_available $domain $path_url || ynh_die "$domain/$path_url is not available, please use an other domain."

#=================================================
# STANDARD RESTORATION STEPS
#=================================================
# RESTORE ALL FILES
#=================================================

# Restore all config and data
ynh_restore

#=================================================
# CREATE A DH FILE
#=================================================

# WARNING : theses command are used in INSTALL, UPGRADE, RESTORE
# For any update do it in all files

# Make dh cert for synapse if it doesn't exist
if [[ ! -e /etc/ssl/private/dh2048.pem ]]
then
    openssl dhparam -out /etc/ssl/private/dh2048.pem -outform PEM -2 2048 -dsaparam 2> /dev/null
    chown root:ssl-cert /etc/ssl/private/dh2048.pem
    chmod 640 /etc/ssl/private/dh2048.pem
fi

#=================================================
# REINSTALL DEPENDENCIES
#=================================================

# WARNING : theses command are used in INSTALL, UPGRADE, RESTORE
# For any update do it in all files
ynh_install_app_dependencies  $dependances

#=================================================
# RECREATE THE DEDICATED USER
#=================================================

ynh_system_user_create $synapse_user /var/lib/matrix-$app
adduser $synapse_user ssl-cert
adduser turnserver ssl-cert

#=================================================
# RECONFIGURE THE TURNSERVER
#=================================================

# To be sure that at the restoration the IP address in coturn config is the same as the real address we remake the coturn config

# Retrieve specific settings
turnserver_tls_port=$(ynh_app_setting_get $app turnserver_tls_port)
turnserver_alt_tls_port=$(ynh_app_setting_get $app turnserver_alt_tls_port)
turnserver_pwd=$(ynh_app_setting_get $app turnserver_pwd)
cli_port=$(ynh_app_setting_get $app cli_port)

# WARNING : these commands are used in INSTALL, UPGRADE
# For any update do it in all files

coturn_config_path="/etc/matrix-$app/coturn.conf"

cp ../settings/conf/turnserver.conf "$coturn_config_path"

ynh_replace_string __APP__ $app "$coturn_config_path"
ynh_replace_string __TURNPWD__ $turnserver_pwd "$coturn_config_path"
ynh_replace_string __DOMAIN__ $domain "$coturn_config_path"
ynh_replace_string __TLS_PORT__ $turnserver_tls_port "$coturn_config_path"
ynh_replace_string __TLS_ALT_PORT__ $turnserver_alt_tls_port "$coturn_config_path"
ynh_replace_string __CLI_PORT__ $cli_port "$coturn_config_path"

# Get public IP and set as external IP for coturn
# note : '|| true' is used to ignore the errors if we can't get the public ipv4 or ipv6
public_ip4="$(curl ip.yunohost.org)" || true
public_ip6="$(curl ipv6.yunohost.org)" || true

if [[ -n "$public_ip4" ]] && ynh_validate_ip4 "$public_ip4"
then
    ynh_replace_string '__IPV4__' "$public_ip4" "$coturn_config_path"
else
    ynh_replace_string '__IPV4__,' "" "$coturn_config_path"
fi

if [[ -n "$public_ip6" ]] && ynh_valide_ip6 "$public_ip6"
then
    ynh_replace_string '__IPV6__' "$public_ip6" "$coturn_config_path"
else
    ynh_replace_string ',__IPV6__' "" "$coturn_config_path"
fi

ynh_store_file_checksum "$coturn_config_path"

#=================================================
# SPECIFIC RESTORATION
#=================================================
# OPEN THE PORT
#=================================================

# Ouvre le port dans le firewall
yunohost firewall allow TCP $synapse_tls_port > /dev/null 2>&1
yunohost firewall allow Both $turnserver_tls_port > /dev/null 2>&1
yunohost firewall allow Both $turnserver_alt_tls_port > /dev/null 2>&1

#=================================================
# SETUP SSOWAT
#=================================================

# Open access to server without a button the home
# The script "add_sso_conf.py" will just add en entry for the path "/_matrix" in the sso conf.json.persistent file in the cathegory "skipped_urls".
python3 ../settings/conf/add_sso_conf.py || ynh_die "Your file /etc/ssowat/conf.json.persistent doesn't respect the json syntax. Please fix the syntax to install this app. For more information see here: https://github.com/YunoHost-Apps/synapse_ynh/issues/32"

#=================================================
# RESTORE THE POSTGRESQL DATABASE
#=================================================

ynh_psql_test_if_first_run
ynh_psql_create_user $synapse_db_user $synapse_db_pwd
ynh_psql_execute_as_root \
"CREATE DATABASE $synapse_db_name
 ENCODING 'UTF8'
 LC_COLLATE='C'
 LC_CTYPE='C'
 template=template0
 OWNER $synapse_db_user;"
ynh_psql_execute_file_as_root "${YNH_CWD}/dump.sql" "$synapse_db_name"

#=================================================
# RESTORE SYSTEMD
#=================================================

systemctl daemon-reload
systemctl enable matrix-$app.service

#=================================================
# SETUP LOGROTATE
#=================================================

ynh_use_logrotate /var/log/matrix-$app

#=================================================
# GENERIC FINALIZATION
#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================

# WARNING : theses command are used in INSTALL, UPGRADE, RESTORE (3 times)
# For any update do it in all files
chown $synapse_user:root -R $final_path
chmod 770 $final_path/Coturn_config_rotate.sh
chown $synapse_user:root -R /var/lib/matrix-$app
chown $synapse_user:root -R /var/log/matrix-$app
chown $synapse_user:root -R /etc/matrix-$app
chmod u=rwX,g=rX,o= -R /etc/matrix-$app
chmod 600 /etc/matrix-$app/$domain.signing.key
setfacl -R -m user:turnserver:rX  /etc/matrix-$app
setfacl -R -m user:turnserver:rwX  /var/log/matrix-$app

#=================================================
# ADVERTISE SERVICE IN ADMIN PANEL
#=================================================

yunohost service add matrix-$app -l "/var/log/matrix-$app/homeserver.log"
yunohost service add coturn-$app

#=================================================
# RELOAD NGINX, SYNAPSE AND COTURN
#=================================================

systemctl reload nginx.service
systemctl restart coturn-$app.service
ynh_check_starting "Synapse now listening on TCP port $synapse_tls_port" "/var/log/matrix-$app/homeserver.log" 300 "matrix-$app"

#=================================================
# SETUP FAIL2BAN
#=================================================

systemctl try-reload-or-restart fail2ban

#=================================================
# SEND A README FOR THE ADMIN
#=================================================

# WARNING : theses command are used in INSTALL, RESTORE
# For any update do it in all files

message="To federate this app you need to add this line in your DNS configuration:

_matrix._tcp.$domain. 3600    IN      SRV     10 0 $synapse_tls_port $domain.

You also need to open the TCP port $synapse_tls_port on your ISP box if it's not automatically done.

Your synapse server also implements a turnserver (for VoIP), to have this fully functional please read the 'Turnserver' section in the README available here: https://github.com/YunoHost-Apps/synapse_ynh .

If you're facing an issue or want to improve this app, please open a new issue in this project: https://github.com/YunoHost-Apps/synapse_ynh"

ynh_send_readme_to_admin "$message"