#!/bin/bash
# panel-migrate-mysql-users <podman container with old datadir>
# Recreates every localhost MySQL user (same password hash) and its database grants on this server.
set -euo pipefail
c="${1:?container}"
podman exec "$c" mysql -uroot -N -r -e "
 select concat('CREATE USER IF NOT EXISTS ', quote(user), '@''localhost'' IDENTIFIED WITH mysql_native_password AS ', quote(authentication_string), ';')
   from mysql.user where host='localhost' and plugin='mysql_native_password' and user not in ('root','mysql.sys','mysql.session','mysql.infoschema','debian-sys-maint','cpses') and user not like 'cpses%';
 select concat('GRANT ALL PRIVILEGES ON \`', replace(db,'\`',''), '\`.* TO ', quote(user), '@''localhost'';')
   from mysql.db where host='localhost' and user not like 'cpses%' and user <> 'root' and db not in ('performance_schema','mysql','sys','information_schema');" > /root/migrate/users.sql
mysql < /root/migrate/users.sql
mysql -e "FLUSH PRIVILEGES"
echo "users: $(grep -c '^CREATE USER' /root/migrate/users.sql)  grants: $(grep -c '^GRANT' /root/migrate/users.sql)"
