backup_dir="$1/conf/ynh/mysql"

# ensure that mysql is running
service mysql status >/dev/null 2>&1 \
  || service mysql start

# retrieve current and new password
[ -f /etc/yunohost/mysql ] \
  && curr_pwd=$(sudo cat /etc/yunohost/mysql)
new_pwd=$(sudo cat "${backup_dir}/root_pwd" || sudo cat "${backup_dir}/mysql")
[ -z "$curr_pwd" ] && curr_pwd="yunohost"
[ -z "$new_pwd" ] && {
    . /usr/share/yunohost/helpers.d/string
    new_pwd=$(ynh_string_random 10)
}

# attempt to change it
sudo mysqladmin -s -u root -p"$curr_pwd" password "$new_pwd" || {
  . /usr/share/yunohost/helpers.d/package

  echo "It seems that you have already configured MySQL." \
    "YunoHost needs to have a root access to MySQL to runs its" \
    "applications, and is going to reset the MySQL root password." \
    "You can find this new password in /etc/yunohost/mysql." >&2

  # retrieve MySQL package provider
  ynh_package_is_installed "mariadb-server-10.0" \
    && mysql_pkg="mariadb-server-10.0" \
    || mysql_pkg="mysql-server-5.5"

  # set new password with debconf
  sudo debconf-set-selections << EOF
$mysql_pkg mysql-server/root_password password $new_pwd
$mysql_pkg mysql-server/root_password_again password $new_pwd
EOF

  # reconfigure Debian package
  sudo dpkg-reconfigure -freadline -u "$mysql_pkg" 2>&1
}

# store new root password
echo "$new_pwd" | sudo tee /etc/yunohost/mysql
sudo chmod 400 /etc/yunohost/mysql

# reload the grant tables
sudo mysqladmin -s -u root -p"$new_pwd" reload