#!/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/>.
#

# Create a dedicated fail2ban config (jail and filter conf files)
#
# usage: ynh_config_add_fail2ban --logpath=log_file --failregex=filter
# | arg: --logpath=   - Log file to be checked by fail2ban
# | arg: --failregex= - Failregex to be looked for by fail2ban
#
# If --logpath / --failregex are provided, the helper will generate the appropriate conf using these.
#
# Otherwise, it will assume that the app provided templates, namely
# `../conf/f2b_jail.conf` and `../conf/f2b_filter.conf`
#
# They will typically look like (for example here for synapse):
#
# ```toml
# f2b_jail.conf:
#     [__APP__]
#     enabled = true
#     port = http,https
#     filter = __APP__
#     logpath = /var/log/__APP__/logfile.log
#     maxretry = 5
# ```
#
# ```toml
# f2b_filter.conf:
#     [INCLUDES]
#     before = common.conf
#     [Definition]
#
#     # Part of regex definition (just used to make more easy to make the global regex)
#     __synapse_start_line = .? \- synapse\..+ \-
#
#    # Regex definition.
#    failregex = ^%(__synapse_start_line)s INFO \- POST\-(\d+)\- <HOST> \- \d+ \- Received request\: POST /_matrix/client/r0/login\??<SKIPLINES>%(__synapse_start_line)s INFO \- POST\-\1\- Got login request with identifier: \{u'type': u'm.id.user', u'user'\: u'(.+?)'\}, medium\: None, address: None, user\: u'\5'<SKIPLINES>%(__synapse_start_line)s WARNING \- \- (Attempted to login as @\5\:.+ but they do not exist|Failed password login for user @\5\:.+)$
#
#     ignoreregex =
# ```
#
# ##### Regarding the the `failregex` option
#
# regex to match the password failure messages in the logfile. The host must be
# matched by a group named "`host`". The tag "`<HOST>`" can be used for standard
# IP/hostname matching and is only an alias for `(?:::f{4,6}:)?(?P<host>[\w\-.^_]+)`
#
# You can find some more explainations about how to make a regex on [the official fail2ban documentation](https://www.fail2ban.org/wiki/index.php/MANUAL_0_8#Filters).
#
# To validate your regex you can test with this command:
#
# ```bash
# fail2ban-regex /var/log/YOUR_LOG_FILE_PATH /etc/fail2ban/filter.d/YOUR_APP.conf
# ```
ynh_config_add_fail2ban() {
    # ============ Argument parsing =============
    local -A args_array=([l]=logpath= [r]=failregex=)
    local logpath
    local failregex
    ynh_handle_getopts_args "$@"
    # ===========================================

    # If failregex is provided, Build a config file on-the-fly using $logpath and $failregex
    if [[ -n "${failregex:-}" ]]; then
        test -n "$logpath" || ynh_die "ynh_config_add_fail2ban expects a logfile path as first argument and received nothing."

        echo "
[__APP__]
enabled = true
port = http,https
filter = __APP__
logpath = __LOGPATH__
maxretry = 5
" > "$YNH_APP_BASEDIR/conf/f2b_jail.conf"

        echo "
[INCLUDES]
before = common.conf
[Definition]
failregex = __FAILREGEX__
ignoreregex =
" > "$YNH_APP_BASEDIR/conf/f2b_filter.conf"
    fi

    ynh_config_add --template="f2b_jail.conf" --destination="/etc/fail2ban/jail.d/$app.conf"
    ynh_config_add --template="f2b_filter.conf" --destination="/etc/fail2ban/filter.d/$app.conf"

    # Create the folder and logfile if they doesn't exist,
    # as fail2ban require an existing logfile before configuration
    local logdir=$(dirname "$logpath")
    if [ ! -d "$logdir" ]; then
        mkdir -p "$logdir"
        # Make sure log folder's permissions are correct
        chown "$app:$app" "$logdir"
        chmod u=rwX,g=rX,o= "$logdir"
    fi

    if [ ! -f "$logpath" ]; then
        touch "$logpath"
        # Make sure log file's permissions are correct
        chown "$app:$app" "$logpath"
        chmod u=rwX,g=rX,o= "$logpath"
    fi

    ynh_systemctl --service=fail2ban --action=reload --wait_until="(Started|Reloaded) fail2ban.service" --log_path=systemd

    local fail2ban_error="$(journalctl --no-hostname --unit=fail2ban | tail --lines=50 | grep "WARNING.*$app.*")"
    if [[ -n "$fail2ban_error" ]]; then
        ynh_print_warn "Fail2ban failed to load the jail for $app"
        ynh_print_warn "${fail2ban_error#*WARNING}"
    fi
}

# Remove the dedicated fail2ban config (jail and filter conf files)
#
# usage: ynh_config_remove_fail2ban
ynh_config_remove_fail2ban() {
    ynh_safe_rm "/etc/fail2ban/jail.d/$app.conf"
    ynh_safe_rm "/etc/fail2ban/filter.d/$app.conf"
    ynh_systemctl --service=fail2ban --action=reload
}
