#!/bin/bash

# Create a dedicated fail2ban config (jail and filter conf files)
#
# usage 1: ynh_add_fail2ban_config --logpath=log_file --failregex=filter [--max_retry=max_retry] [--ports=ports]
# | arg: -l, --logpath=   - Log file to be checked by fail2ban
# | arg: -r, --failregex= - Failregex to be looked for by fail2ban
# | arg: -m, --max_retry= - Maximum number of retries allowed before banning IP address - default: 3
# | arg: -p, --ports=     - Ports blocked for a banned IP address - default: http,https
#
# usage 2: ynh_add_fail2ban_config --use_template
# | 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_add_config` 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 = 3
# ```
# ```
# 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_add_fail2ban_config() {
    # Declare an array to define the options of this helper.
    local legacy_args=lrmptv
    local -A args_array=([l]=logpath= [r]=failregex= [m]=max_retry= [p]=ports= [t]=use_template)
    local logpath
    local failregex
    local max_retry
    local ports
    local use_template
    # Manage arguments with getopts
    ynh_handle_getopts_args "$@"
    max_retry=${max_retry:-3}
    ports=${ports:-http,https}
    use_template="${use_template:-0}"

    if [ "$use_template" -ne 1 ]; then
        # Usage 1, no template. Build a config file from scratch.
        test -n "$logpath" || ynh_die --message="ynh_add_fail2ban_config expects a logfile path as first argument and received nothing."
        test -n "$failregex" || ynh_die --message="ynh_add_fail2ban_config expects a failure regex as second argument and received nothing."

        echo "
[__APP__]
enabled = true
port = __PORTS__
filter = __APP__
logpath = __LOGPATH__
maxretry = __MAX_RETRY__
" >"$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_add_config --template="f2b_jail.conf" --destination="/etc/fail2ban/jail.d/$app.conf"
    ynh_add_config --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_name=fail2ban --action=reload --line_match="(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_err --message="Fail2ban failed to load the jail for $app"
        ynh_print_warn --message="${fail2ban_error#*WARNING}"
    fi
}

# Remove the dedicated fail2ban config (jail and filter conf files)
#
# usage: ynh_remove_fail2ban_config
#
# Requires YunoHost version 3.5.0 or higher.
ynh_remove_fail2ban_config() {
    ynh_secure_remove --file="/etc/fail2ban/jail.d/$app.conf"
    ynh_secure_remove --file="/etc/fail2ban/filter.d/$app.conf"
    ynh_systemd_action --service_name=fail2ban --action=reload
}