#!/bin/sh

set -e

. /usr/share/debconf/confmodule

#
# Skip, if we are not in "configure" state
#
if [ "$1" != "configure" ]; then
        echo "I: Skipping configuration"
        exit 0
fi

#DEBHELPER#

#
# Add symlinks for the monit script
# 
monit_dir="/etc/symbiosis/monit.d"
mkdir -p "$monit_dir"

for i in mysqld; do
  monit_script="/usr/share/symbiosis/monit/checks/$i"
  link_target="$monit_dir/$i"

  if [ -x "$monit_script" ] && [ ! -e "$link_target" ]; then
    echo "I: Adding symlink for Symbiosis Monit script for $i"
    ln -s "$monit_script" "$link_target" || true
  fi
done

#
# Restart mysql just in case the config has been modified.
#
invoke-rc.d mysql restart

#
# And upgrade mysql, if we can.
#
if [ -x /usr/bin/mysql_upgrade ] ; then
  echo "I: Upgrading MySQL"
  /usr/bin/mysql_upgrade --defaults-file=/etc/mysql/debian.cnf || true
fi

#
# Add an admin user with user/password authentication for phpmyadmin if one doesn't already exist
#
if grep -qx 'password = ' /etc/mysql/debian.cnf && [ "$(mysql -u root -se "select exists(select user from mysql.user where user = 'admin');")" = "0" ] ; then
  echo "I: Adding 'admin'@'localhost' MySQL user"
  if [ -e /etc/first-boot.d/.mysql.hash ]; then
    mysql -u root -e "grant all privileges on *.* to 'admin'@'localhost' identified by password '*$(cat /etc/first-boot.d/.mysql.hash)' with grant option;"
  else
    db_get symbiosis-mysql/admin_password
    mysql -u root -e "grant all privileges on *.* to 'admin'@'localhost' identified by '$RET' with grant option;"
  fi
fi

exit 0
