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

FIRST_CALL_TO_LOGROTATE="true"

# Add a logrotate configuration to manage log files / log directory
#
# usage: ynh_config_add_logrotate [/path/to/log/file/or/folder]
#
# If not argument is provided, `/var/log/$app/*.log` is used as default.
#
# The configuration is autogenerated by YunoHost
# (ie it doesnt come from a specific app template like nginx or systemd conf)
ynh_config_add_logrotate() {

    local logfile="${1:-}"

    set -o noglob
    if [[ -z "$logfile" ]]; then
        logfile="/var/log/${app}/*.log"
    elif [[ "${logfile##*.}" != "log" ]] && [[ "${logfile##*.}" != "txt" ]]; then
        logfile="$logfile/*.log"
    fi
    set +o noglob

    for stuff in $logfile; do
        # Make sure the permissions of the parent dir are correct (otherwise the config file could be ignored and the corresponding logs never rotated)
        local dir=$(dirname "$stuff")
        mkdir --parents "$dir"
        chmod 750 "$dir"
        chown "$app:$app" "$dir"
    done

    local tempconf="$(mktemp)"
    cat << EOF > "$tempconf"
$logfile {
    # Rotate if the logfile exceeds 100Mo
    size 100M
    # Keep 12 old log maximum
    rotate 12
    # Compress the logs with gzip
    compress
    # Compress the log at the next cycle. So keep always 2 non compressed logs
    delaycompress
    # Copy and truncate the log to allow to continue write on it. Instead of moving the log.
    copytruncate
    # Do not trigger an error if the log is missing
    missingok
    # Do not rotate if the log is empty
    notifempty
    # Keep old logs in the same dir
    noolddir
}
EOF

    if [[ "$FIRST_CALL_TO_LOGROTATE" == "true" ]]; then
        cat "$tempconf" > "/etc/logrotate.d/$app"
    else
        cat "$tempconf" >> "/etc/logrotate.d/$app"
    fi

    FIRST_CALL_TO_LOGROTATE="false"

    chmod 644 "/etc/logrotate.d/$app"
}

# Remove the app's logrotate config.
#
# usage:ynh_config_remove_logrotate
ynh_config_remove_logrotate() {
    if [ -e "/etc/logrotate.d/$app" ]; then
        rm "/etc/logrotate.d/$app"
    fi
}
