#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/fix_mariadb_password_expired           Copyright 2021 cPanel, L.L.C.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package autofixer2::fix_mariadb_password_expired;

use strict;
use warnings;

BEGIN { unshift @INC, '/usr/local/cpanel'; }

exit run() unless caller;

sub run {

    return 0 unless supported_on_this_major( 98, 98 );    # Set this to the Min/Max we support this autofixer on.

    require Cpanel::MysqlUtils::Version;
    require Cpanel::MysqlUtils::Connect;
    require Cpanel::MariaDB;

    my $version = eval { Cpanel::MysqlUtils::Version::mysqlversion() };
    return 0 if !$version;
    return 0 if !Cpanel::MariaDB::version_is_mariadb($version);

    my $dbh = eval { Cpanel::MysqlUtils::Connect::get_dbi_handle() };
    return 0 if !$dbh;

    my $query;

    # The problem is password_last_changed is set to zero. So we set password_last_changed to the current time.
    # The query syntax is a little different on MariaDB 10.5 due to the global_priv table.
    #
    if ( $version > 10.3 ) {
        $query = "UPDATE mysql.global_priv SET Priv=JSON_SET(Priv, '\$.password_last_changed', UNIX_TIMESTAMP()) WHERE JSON_VALUE(Priv, '\$.password_last_changed') = '0'";
    }
    else {
        $query = "UPDATE mysql.user SET password_last_changed = NOW() WHERE password_last_changed = '0000-00-00 00:00:00'";
    }

    eval { $dbh->do($query); };
    eval { $dbh->do('FLUSH PRIVILEGES'); };

    return 1;
}

# Do we run this code?
sub supported_on_this_major {
    my ( $min_ver, $max_ver ) = @_;

    my $major = get_major_version();

    return 0 if $major < $min_ver;
    return 0 if $major > $max_ver;

    return 1;
}

sub get_major_version {
    my $major_version;

    if ( open( my $fh, '<', '/usr/local/cpanel/version' ) ) {
        my $full_version = <$fh>;
        chomp $full_version;
        close($fh);
        ($major_version) = $full_version =~ /^[0-9]+\.([0-9]+)/;
    }

    # Safe default.
    return $major_version || 30;
}

1;
