#!/bin/bash

set -e
. /usr/share/yunohost/helpers

do_pre_regen() {
  pending_dir=$1

  cd /usr/share/yunohost/templates/mysql

  install -D -m 644 my.cnf "${pending_dir}/etc/mysql/my.cnf"
}

do_post_regen() {
  regen_conf_files=$1

  if [[ ! -d /var/lib/mysql/mysql ]]
  then
      # dpkg-reconfigure will initialize mysql (if it ain't already)
      # It enabled auth_socket for root, so no need to define any root password...
      # c.f. : cat /var/lib/dpkg/info/mariadb-server-10.3.postinst | grep install_db -C3
      MYSQL_PKG="$(dpkg --list | sed -ne 's/^ii  \(mariadb-server-[[:digit:].]\+\) .*$/\1/p')"
      dpkg-reconfigure -freadline -u "$MYSQL_PKG" 2>&1

      systemctl -q is-active mariadb.service \
        || systemctl start mariadb

      sleep 5

      echo "" | mysql && echo "Can't connect to mysql using unix_socket auth ... something went wrong during initial configuration of mysql !?" >&2
  fi

  # Legacy code to get rid of /etc/yunohost/mysql ...
  # Nowadays, we can simply run mysql while being run as root of unix_socket/auth_socket is enabled...
  if [ -f /etc/yunohost/mysql ]; then

      # This is a trick to check if we're able to use mysql without password
      # Expect instances installed in stretch to already have unix_socket
      #configured, but not old instances from the jessie/wheezy era
      if ! echo "" | mysql 2>/dev/null
      then
          password="$(cat /etc/yunohost/mysql)"
          # Enable plugin unix_socket for root on localhost
          mysql -u root -p"$password" <<< "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED WITH unix_socket WITH GRANT OPTION;"
      fi

      # If now we're able to login without password, drop the mysql password
      if echo "" | mysql 2>/dev/null
      then
          rm /etc/yunohost/mysql
      else
          echo "Can't connect to mysql using unix_socket auth ... something went wrong while trying to get rid of mysql password !?" >&2
      fi
  fi

  # mysql is supposed to be an alias to mariadb... but in some weird case is not
  # c.f. https://forum.yunohost.org/t/mysql-ne-fonctionne-pas/11661
  # Playing with enable/disable allows to recreate the proper symlinks.
  if [ ! -e /etc/systemd/system/mysql.service ]
  then
      systemctl stop mysql -q
      systemctl disable mysql -q
      systemctl disable mariadb -q
      systemctl enable mariadb -q
      systemctl is-active mariadb -q || systemctl start mariadb
  fi

  [[ -z "$regen_conf_files" ]] \
    || systemctl restart mysql
}

FORCE=${2:-0}
DRY_RUN=${3:-0}

case "$1" in
  pre)
    do_pre_regen $4
    ;;
  post)
    do_post_regen $4
    ;;
  *)
    echo "hook called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac

exit 0
