#!/bin/bash

[ "$(CreoleGet activer_mysql)" = "non" ] && exit 0

fileroot="binlog"
container_path=$(CreoleGet container_path_mysql)
index_file="${container_path}/var/lib/mysql/${fileroot}.index"

if [ "$(CreoleGet mysql_activer_binlog)" = "oui" ]
then
    retention_in_hours=$(CreoleGet mysql_binlog_retention 0)
    retention_in_seconds=$(expr $retention_in_hours \* 3600)

    request="use mysql; PURGE BINARY LOGS BEFORE NOW() - INTERVAL $retention_in_hours HOUR;"

    # clean /var/lib/mysql/binlog.index in case log files would have been manually removed
    # to prevent purge action failure

    pushd "$(dirname "$index_file")" >/dev/null

    for log_file in $(cat "$index_file");
    do
        [ ! -e "$(realpath "${log_file}")" ] && sed -i -e ";$log_file;d" $index_file
    done
    popd >/dev/null

    # purge log files
    CreoleRun "mysql --defaults-file=/etc/mysql/debian.cnf -e '$request'" "mysql"
elif [ -e "$index_file" ]
then
    pushd $(dirname "$index_file") >/dev/null
    for log_file in $(cat "$index_file")
    do
        rm -f "$(realpath "$log_file")"
    done
    rm -f "$index_file"
    popd >/dev/null
fi

exit 0
