#!/usr/bin/env bash
#
# Copyright (c) 2024 YunoHost Contributors
#
# This file is part of YunoHost (see https://yunohost.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

set -e

# Source YNH helpers
# shellcheck source=../../helpers/helpers
source /usr/share/yunohost/helpers

do_pre_regen() {
    pending_dir=$1

    cd /usr/share/yunohost/conf/ssh

    # Support different strategy for security configurations
    export compatibility="$(jq -r '.ssh_compatibility' <<< "$YNH_SETTINGS")"
    export port="$(jq -r '.ssh_port' <<< "$YNH_SETTINGS")"
    export password_authentication="$(jq -r '.ssh_password_authentication' <<< "$YNH_SETTINGS" | int_to_bool)"
    export ssh_keys=$(ls /etc/ssh/ssh_host_{ed25519,rsa,ecdsa}_key 2> /dev/null || true)

    # do not listen to IPv6 if unavailable
    [[ -f /proc/net/if_inet6 ]] && ipv6_enabled=true || ipv6_enabled=false
    export ipv6_enabled

    ynh_render_template "sshd_config" "${pending_dir}/etc/ssh/sshd_config"
}

do_post_regen() {
    regen_conf_files=$1

    # If no file changed, there's nothing to do

    [[ -n "$regen_conf_files" ]] || return 0

    # Enforce permissions for /etc/ssh/sshd_config
    chown root:root "/etc/ssh/sshd_config"
    chmod 644 "/etc/ssh/sshd_config"

    systemctl restart ssh
}

"do_$1_regen" "$(echo "${*:2}" | xargs)"
