#!/bin/bash

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

source ./_common.sh
source /usr/share/yunohost/helpers

# Stop script if errors
ynh_abort_if_errors

#=================================================
# RETRIEVE ARGUMENTS
#=================================================

app=$YNH_APP_INSTANCE_NAME
access_domain=$(ynh_app_setting_get --app=$app --key=access_domain)
domain=$(ynh_app_setting_get --app=$app --key=domain)

#=================================================
# SHOW_CONFIG FUNCTION FOR 'SHOW' COMMAND
#=================================================

show_config() {
    if [ ! -z $access_domain ]
    then
        ynh_return "YNH_CONFIG_MAIN_ACCESS_DOMAIN_ACCESS_DOMAIN=$(echo $access_domain | sed "s@;@ @g")"
    else
        ynh_return "YNH_CONFIG_MAIN_ACCESS_DOMAIN_ACCESS_DOMAIN=$domain"
    fi
}

#=================================================
# MODIFY THE CONFIGURATION
#=================================================

apply_config() {
    access_domain=${YNH_CONFIG_MAIN_ACCESS_DOMAIN_ACCESS_DOMAIN:-$access_domain}
    ynh_app_setting_set --app=$app --key=access_domain --value=$access_domain

    access_domain=$(ynh_app_setting_get --app=$app --key=access_domain)
    access_domains=$(echo $access_domain | sed "s@;@ @g")

    nginx_conf_path=/etc/nginx/conf.d/$domain.d/$app.conf
    ynh_delete_file_checksum --file=$nginx_conf_path
    ynh_replace_string \
        --match_string='more_set_headers "Content-Security-Policy: frame-ancestors '"'self'"'.*";' \
        --replace_string='more_set_headers "Content-Security-Policy: frame-ancestors '"'self' $access_domains"'";' \
        --target_file=$nginx_conf_path
    ynh_store_file_checksum --file=$nginx_conf_path

    systemctl reload nginx
}

#=================================================
# GENERIC FINALIZATION
#=================================================
# SELECT THE ACTION FOLLOWING THE GIVEN ARGUMENT
#=================================================
case $1 in
    show) show_config;;
    apply) apply_config;;
esac