#!/bin/bash
# Set the MySQL password of a site's DB user to the one in its bitrix/.settings.php, then test the login.
# The password is never printed. usage: set-db-pass.sh /home/bitrix/ext_www/<site>
set -euo pipefail
F=$1/bitrix/.settings.php
php -r '
$c = (include $argv[1])["connections"]["value"]["default"];
$q = fn($s) => "'"'"'" . str_replace(["\\\\", "'"'"'"], ["\\\\\\\\", "\\\\'"'"'"], $s) . "'"'"'";
foreach (["localhost", "%"] as $h) {
    echo "ALTER USER IF EXISTS ", $q($c["login"]), "@", $q($h), " IDENTIFIED BY ", $q($c["password"]), ";\n";
}' "$F" | mysql
umask 077; T=$(mktemp)
php -r '$c = (include $argv[1])["connections"]["value"]["default"]; echo "[client]\nuser=", $c["login"], "\npassword=\"", $c["password"], "\"\nsocket=", $argv[2], "\n";' "$F" "$(mysql -N -e 'SELECT @@socket')" > "$T"
mysql --defaults-file="$T" -N -e "SELECT CURRENT_USER(), DATABASE(), (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '$(php -r 'echo (include $argv[1])["connections"]["value"]["default"]["database"];' "$F")')"
rm -f "$T"
