#!/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/sympl/monit.d"
mkdir -p "$monit_dir"

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

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

#
# Restart mysql just in case the config has been modified.
#
service mysql restart

#
# And upgrade mysql, if we can.
#

if [ -x /usr/bin/mysql_upgrade ]; then
  sleep 3
  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, and write into to /root/
#
service mysql start
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"
  # Select password
  MYSQL_PASSWORD="$(openssl rand 200 | base64 | tr -dc '[[:alnum:]]' | cut -c 1-20)"
  echo "I: Password selected"
  # Set password
  mysql --defaults-file=/etc/mysql/debian.cnf -e "grant all privileges on *.* to 'admin'@'localhost' identified by '$MYSQL_PASSWORD' with grant option;"
  echo "I: Password set"
  if [ ! -f /root/.my.cnf ]; then
    echo "I: Saving to /root/.my.cnf"
    # Skip overwriting an existing /root/.my.cnf
    echo "[client]" > /root/.my.cnf
    echo "user=admin" >> /root/.my.cnf
    echo "password=$MYSQL_PASSWORD" >> /root/.my.cnf
  fi
  # Write the password as plaintext to the /root dir
  echo "I: Saving to /root/mysql_admin_password"
  echo "$MYSQL_PASSWORD" > /root/mysql_admin_password
  # Lock down permissions
  echo "I: Restricting permissions"
  chmod 600 /root/mysql_admin_password /root/.my.cnf
  chown root:root /root/mysql_admin_password /root/.my.cnf
  echo "I: done"
fi

service mysql stop

exit 0
