#!/bin/bash

# Create a dedicated fail2ban config (jail and filter conf files)
#
# usage 1: ynh_config_add_fail2ban --logpath=log_file --failregex=filter
# | arg: -l, --logpath=   - Log file to be checked by fail2ban
# | arg: -r, --failregex= - Failregex to be looked for by fail2ban
#
# usage 2: ynh_config_add_fail2ban
# | arg: -t, --use_template - Use this helper in template mode
#
# This will use a template in `../conf/f2b_jail.conf` and `../conf/f2b_filter.conf`
# See the documentation of `ynh_config_add` for a description of the template
# format and how placeholders are replaced with actual variables.
#
# Generally your template will look like that by example (for synapse):
# ```
# f2b_jail.conf:
#     [__APP__]
#     enabled = true
#     port = http,https
#     filter = __APP__
#     logpath = /var/log/__APP__/logfile.log
#     maxretry = 5
# ```
# ```
# 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 =
# ```
#
# -----------------------------------------------------------------------------
#
# Note about 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 here :
# https://www.fail2ban.org/wiki/index.php/MANUAL_0_8#Filters
#
# To validate your regex you can test with this command:
# ```
# fail2ban-regex /var/log/YOUR_LOG_FILE_PATH /etc/fail2ban/filter.d/YOUR_APP.conf
# ```
#
# Requires YunoHost version 4.1.0 or higher.
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"

    # if "$logpath" doesn't exist (as if using --use_template argument), assign
    # "$logpath" using the one in the previously generated fail2ban conf file
    if [ -z "${logpath:-}" ]; then
        # the first sed deletes possibles spaces and the second one extract the path
        logpath=$(grep "^logpath" "/etc/fail2ban/jail.d/$app.conf" | sed "s/ //g" | sed "s/logpath=//g")
    fi

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

    ynh_systemd_action --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
#
# Requires YunoHost version 3.5.0 or higher.
ynh_config_remove_fail2ban() {
    ynh_safe_rm "/etc/fail2ban/jail.d/$app.conf"
    ynh_safe_rm "/etc/fail2ban/filter.d/$app.conf"
    ynh_systemd_action --service=fail2ban --action=reload
}
