#!/bin/bash
function wpdbimport() {
     cpuser="$(stat -c %U .)"
     pass="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 1)"
     prefix="$(wp config get table_prefix)"
     dbstuff="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 7 | head -n 1)"
     name="${cpuser:0:8}_${dbstuff}"
     uapi Mysql create_database name=$name 1>/dev/null
     uapi Mysql create_user name=$name password=$pass 1>/dev/null
     uapi Mysql set_privileges_on_database user=$name database=$name privileges=ALL%20PRIVILEGES 1>/dev/null
     echo "name ${name} password ${pass} user ${name}"
     if [ -f wp-config.php ]; then
          mv wp-config.php .old-wp-config.php
          mysql_host="$(uapi Mysql locate_server remote_host 2>/dev/null | grep -oP '(?<=host: ).+')"
          wp config create --dbname=$name --dbuser=$name --dbpass=$pass --dbprefix=$prefix --dbhost=$mysql_host --force
          wp config set WP_DEBUG false --type=variable
          mysql --user=$name -f --password=$pass -h $mysql_host $name <$1
     fi
     if [ "$#" -eq 1 ]; then
          mysql --user=$name -f --password=$pass -h $mysql_host $name <$1
     fi
}
wpdbimport $1
