#!/bin/bash

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
}