#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - bin/updatephpmyadmin                   Copyright(c) 2013 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

## cpdev: installs to /usr/local/cpanel/base/3rdparty/phpMyAdmin

use strict;
use Cpanel::LoadFile        ();
use Cpanel::MysqlUtils      ();
use Cpanel::SafeDir::MK     ();
use Cpanel::StringFunc      ();
use Cpanel::MysqlUtils      ();
use Cpanel::Logger          ();
use Cpanel::Rand            ();
use Cpanel::FileUtils::Copy ();
use Cpanel::SafeRun::Simple ();
use Cpanel::Hostname        ();
use Cpanel::Patch           ();

my $logger = Cpanel::Logger->new();

my $force = grep( /--force/, @ARGV ) ? 1 : 0;

my $mysql_version = Cpanel::MysqlUtils::mysqlversion();
unless ( defined $mysql_version && $mysql_version ne '' ) {
    $logger->die("Failed to fetch basic MySQL information. Cannot update phpMyAdmin.");
}

## increment $PHPMYADMIN_VERSION upon new version of phpmyadmin
## increment $phpmyadmin_cpanel upon next cPanel patch
my $PHPMYADMIN_VERSION = '4.3.8-all-languages';
my $internal_version   = '.cp1';

## this is compared to the version number in
## '/usr/local/cpanel/base/3rdparty/phpMyAdmin/cpversion'
my $phpmyadmin_cpanel = $PHPMYADMIN_VERSION . $internal_version;

my $DIR = '/usr/local/cpanel/base/3rdparty';

my $versionfile    = "$DIR/phpMyAdmin/cpversion";
my $currentversion = Cpanel::LoadFile::loadfile($versionfile);
## case 34758: check the existence of index.php, which will be missing when crossing from a cPanel
##   version that has the extracted source version to a cPanel version which uses the pristine source
my $index_exists = -e "$DIR/phpMyAdmin/index.php";

my $is_legacy = 0;
my $phpmyadmin_patches;
if ( $phpmyadmin_cpanel eq $currentversion && !$force && $index_exists ) {
    print "phpMyAdmin is up to date. Execute '$0 --force' to force an update.\n";
    exit;
}
else {

    # we need to know which pma family for proper cpanel library extensions
    my $pma_ver_str = $PHPMYADMIN_VERSION;
    $pma_ver_str =~ s/\A(\d+\.\d+\.\d+)\-.*\z/$1/;
    my ( $pma_major, $pma_minor, $pma_rev ) = split( /\./, $pma_ver_str );

    $phpmyadmin_patches = 'phpMyAdmin-' . $pma_major;
    if (   ( $pma_major < 3 )
        || ( $pma_major >= 3 && $pma_minor < 4 ) ) {
        $is_legacy = 1;
    }
}

# grab the phpMyAdmin blowfish secret before blowing away the old version
my $config = "$DIR/phpMyAdmin/config.inc.php";
my $bf_secret;

if ( -e $config && open( my $pma_config_fh, '<', $config ) ) {
    while ( my $line = readline($pma_config_fh) ) {
        if ( $line =~ /^\s*\$cfg\[\'blowfish_secret\'\]\s*\=\s*['"]([a-zA-Z0-9_]+)['"]\s*;/ ) {
            $bf_secret = $1 if $1 ne '__BLOWFISHSECRET__';
            last;
        }
    }
    close $pma_config_fh;
}

my $config_in  = "$DIR/phpMyAdmin/config.sample.inc.php";
my $mysql_host = Cpanel::MysqlUtils::getmydbhost('root') || 'localhost';
my $mysql_port = Cpanel::MysqlUtils::getmydbport('root') || '3306';

# Reset ownership of all files to root:wheel
system 'chown', '-R', 'root:wheel', "$DIR/phpMyAdmin";

if ( !-e $config_in ) {
    die "Default phpMyAdmin configuration template $config_in not found!";
}

# Install new default configuration file
system 'cp', '-f', $config_in, $config;
if ( !-e $config ) {
    die "Failed to install default phpMyAdmin configuration file: $!";
}

# Configuration must be owned by root and readable by cpanel group
chmod 0644, $config;
my ( $cpanel_uid, $cpanel_gid ) = ( getpwnam('cpanelphpmyadmin') )[ 2, 3 ];
$cpanel_uid = $cpanel_uid ? $cpanel_uid : 0;    # Just in case
$cpanel_gid = $cpanel_gid ? $cpanel_gid : 0;    # Just in case
chown 0, $cpanel_gid, $config;

# Update MySQL host in configuration file
Cpanel::StringFunc::regsrep( $config, '(.*)__MYSQLHOST__(.*)', '$1' . $mysql_host . '$2' );
Cpanel::StringFunc::regsrep( $config, '(.*)__MYSQLPORT__(.*)', '$1' . $mysql_port . '$2' );

# Set the blowfish secrert for encrypted session information
$bf_secret = Cpanel::Rand::getranddata(128) if !$bf_secret;
Cpanel::StringFunc::regsrep( $config, '(.*)__BLOWFISHSECRET__(.*)', '$1' . $bf_secret . '$2' );

# Remove the "setup" directory that allow an 'admin' to create new config.inc.php files
if ( -d "$DIR/phpMyAdmin/setup/" ) {
    system 'rm', '-rf', "$DIR/phpMyAdmin/setup/";
    print "Removed feature for generating custom PMA config files.\n";
}

open( my $vh_fh, '>', $versionfile );
print {$vh_fh} $phpmyadmin_cpanel;
close($vh_fh);

print "phpMyAdmin updated to $phpmyadmin_cpanel\n";
