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

# Exit hook on subcommand error or unset variable
set -eu

# Source YNH helpers
# shellcheck source=../../helpers/helpers
source /usr/share/yunohost/helpers

if ! dpkg --list | grep -q '^ii\s*mariadb-server\s'; then
    echo 'mysql/mariadb is not installed, skipping'
    exit 0
fi

do_pre_regen() {
    # Nothing to do
    :
}

do_post_regen() {
    regen_conf_files=$1

    if [[ ! -d /var/lib/mysql/mysql ]]; then
        # dpkg-reconfigure will initialize mysql (if it ain't already)
        # It enabled auth_socket for root, so no need to define any root password...
        # c.f. : cat /var/lib/dpkg/info/mariadb-server-10.3.postinst | grep install_db -C3
        MYSQL_PKG="$(dpkg --list | sed -ne 's/^ii  \(mariadb-server-[[:digit:].]\+\) .*$/\1/p')"
        dpkg-reconfigure -freadline -u "$MYSQL_PKG" 2>&1

        if ! systemctl -q is-active mariadb.service; then
            systemctl start mariadb
        fi
        sleep 5

        if ! echo "" | mysql; then
            echo "Can't connect to mysql using unix_socket auth ... something went wrong during initial configuration of mysql !?" >&2
        fi
    fi

    # mysql is supposed to be an alias to mariadb... but in some weird case is not
    # c.f. https://forum.yunohost.org/t/mysql-ne-fonctionne-pas/11661
    # Playing with enable/disable allows to recreate the proper symlinks.
    if [ ! -e /etc/systemd/system/mysql.service ]; then
        systemctl stop mysql -q
        systemctl disable mysql -q
        systemctl disable mariadb -q
        systemctl enable mariadb -q
        if ! systemctl is-active mariadb -q; then
            systemctl start mariadb
        fi
    fi

    if [[ -n "$regen_conf_files" ]]; then
        systemctl restart mysql
    fi
}

"do_$1_regen" "$(echo "${*:2}" | xargs)"
