#!/bin/bash

set -e

. /usr/share/yunohost/helpers

do_init_regen() {
    if [[ $EUID -ne 0 ]]; then
        echo "You must be root to run this script" 1>&2
        exit 1
    fi

    cd /usr/share/yunohost/conf/nginx

    nginx_dir="/etc/nginx"
    nginx_conf_dir="${nginx_dir}/conf.d"
    mkdir -p "$nginx_conf_dir"

    # install plain conf files
    cp plain/* "$nginx_conf_dir"

    # probably run with init: just disable default site, restart NGINX and exit
    rm -f "${nginx_dir}/sites-enabled/default"

    export compatibility="intermediate"
    ynh_render_template "security.conf.inc" "${nginx_conf_dir}/security.conf.inc"
    ynh_render_template "yunohost_admin.conf" "${nginx_conf_dir}/yunohost_admin.conf"
    ynh_render_template "yunohost_admin.conf.inc" "${nginx_conf_dir}/yunohost_admin.conf.inc"
    ynh_render_template "yunohost_api.conf.inc" "${nginx_conf_dir}/yunohost_api.conf.inc"

    mkdir -p $nginx_conf_dir/default.d/
    cp "redirect_to_admin.conf" $nginx_conf_dir/default.d/

    # Restart nginx if conf looks good, otherwise display error and exit unhappy
    nginx -t 2>/dev/null || {
        nginx -t
        exit 1
    }
    systemctl restart nginx || {
        journalctl --no-pager --lines=10 -u nginx >&2
        exit 1
    }

    exit 0
}

do_pre_regen() {
    pending_dir=$1

    cd /usr/share/yunohost/conf/nginx

    nginx_dir="${pending_dir}/etc/nginx"
    nginx_conf_dir="${nginx_dir}/conf.d"
    mkdir -p "$nginx_conf_dir"

    # install / update plain conf files
    cp plain/* "$nginx_conf_dir"
    # remove the panel overlay if this is specified in settings
    panel_overlay=$(yunohost settings get 'misc.portal.ssowat_panel_overlay_enabled' | int_to_bool)
    if [ "$panel_overlay" == "False" ]; then
        echo "#" >"${nginx_conf_dir}/yunohost_panel.conf.inc"
    fi

    # retrieve variables
    main_domain=$(cat /etc/yunohost/current_host)

    # Support different strategy for security configurations
    export redirect_to_https="$(yunohost settings get 'security.nginx.nginx_redirect_to_https' | int_to_bool)"
    export compatibility="$(yunohost settings get 'security.nginx.nginx_compatibility')"
    export experimental="$(yunohost settings get 'security.experimental.security_experimental_enabled' | int_to_bool)"
    ynh_render_template "security.conf.inc" "${nginx_conf_dir}/security.conf.inc"

    cert_status=$(yunohost domain cert status --json)

    # add domain conf files
    xmpp_domain_list="$(yunohost domain list --features xmpp --output-as json | jq -r ".domains[]")"
    mail_domain_list="$(yunohost domain list --features mail_in mail_out --output-as json | jq -r ".domains[]")"
    for domain in $YNH_DOMAINS; do
        domain_conf_dir="${nginx_conf_dir}/${domain}.d"
        mkdir -p "$domain_conf_dir"
        mail_autoconfig_dir="${pending_dir}/var/www/.well-known/${domain}/autoconfig/mail/"
        mkdir -p "$mail_autoconfig_dir"

        # NGINX server configuration
        export domain
        export domain_cert_ca=$(echo $cert_status \
            | jq ".certificates.\"$domain\".CA_type" \
            | tr -d '"')
        if echo "$xmpp_domain_list" | grep -q "^$domain$"
        then
            export xmpp_enabled="True"
        else
            export xmpp_enabled="False"
        fi
        if echo "$mail_domain_list" | grep -q "^$domain$"
        then
            export mail_enabled="True"
        else
            export mail_enabled="False"
        fi

        ynh_render_template "server.tpl.conf" "${nginx_conf_dir}/${domain}.conf"
        if [ $mail_enabled == "True" ]
        then
            ynh_render_template "autoconfig.tpl.xml" "${mail_autoconfig_dir}/config-v1.1.xml"
        fi

        touch "${domain_conf_dir}/yunohost_local.conf" # Clean legacy conf files

    done

    export webadmin_allowlist_enabled=$(yunohost settings get security.webadmin.webadmin_allowlist_enabled | int_to_bool)
    if [ "$webadmin_allowlist_enabled" == "True" ]; then
        export webadmin_allowlist=$(yunohost settings get security.webadmin.webadmin_allowlist)
    fi
    ynh_render_template "yunohost_admin.conf.inc" "${nginx_conf_dir}/yunohost_admin.conf.inc"
    ynh_render_template "yunohost_api.conf.inc" "${nginx_conf_dir}/yunohost_api.conf.inc"
    ynh_render_template "yunohost_admin.conf" "${nginx_conf_dir}/yunohost_admin.conf"
    mkdir -p $nginx_conf_dir/default.d/
    cp "redirect_to_admin.conf" $nginx_conf_dir/default.d/

    # remove old domain conf files
    conf_files=$(ls -1 /etc/nginx/conf.d \
        | awk '/^[^\.]+\.[^\.]+.*\.conf$/ { print $1 }')
    for file in $conf_files; do
        domain=${file%.conf}
        [[ $YNH_DOMAINS =~ $domain ]] \
            || touch "${nginx_conf_dir}/${file}"
    done

    # remove old mail-autoconfig files
    autoconfig_files=$(ls -1 /var/www/.well-known/*/autoconfig/mail/config-v1.1.xml 2>/dev/null || true)
    for file in $autoconfig_files; do
        domain=$(basename $(readlink -f $(dirname $file)/../..))
        [[ $YNH_DOMAINS =~ $domain ]] \
            || (mkdir -p "$(dirname ${pending_dir}/${file})" && touch "${pending_dir}/${file}")
    done

    # disable default site
    mkdir -p "${nginx_dir}/sites-enabled"
    touch "${nginx_dir}/sites-enabled/default"
}

do_post_regen() {
    regen_conf_files=$1

    if ls -l /etc/nginx/conf.d/*.d/*.conf
    then
        chown root:root /etc/nginx/conf.d/*.d/*.conf
        chmod 644 /etc/nginx/conf.d/*.d/*.conf
    fi

    [ -z "$regen_conf_files" ] && exit 0

    # create NGINX conf directories for domains
    for domain in $YNH_DOMAINS; do
        mkdir -p "/etc/nginx/conf.d/${domain}.d"
    done

    # Reload nginx if conf looks good, otherwise display error and exit unhappy
    nginx -t 2>/dev/null || {
        nginx -t
        exit 1
    }
    pgrep nginx && systemctl reload nginx || {
        journalctl --no-pager --lines=10 -u nginx >&2
        exit 1
    }
}

do_$1_regen ${@:2}
