#!/bin/bash
. /usr/share/jsjinstalltools/GetVersion
if [ ${VERSION_ID/./} -ge 120 ]; then
  systemctl is-active mariadb.service
  RET=$?
else
  rcmysql status
  RET=$?
fi
if [ ! -f /usr/bin/mimencode ]; then
  zypper -n in -l metamail
fi
if [ $RET != 0 ] ; then
  if [ ${VERSION_ID/./} -ge 120 ]; then
    systemctl start mariadb.service
    systemctl enable mariadb.service
  else
    rcmysql start
    insserv mysql
  fi
fi
ADMINPW=$1
if [ $ADMINPW != - ]; then
  mysqladmin password $ADMINPW
  MPADMINPW="-p$ADMINPW"
fi
# generate random password of length 16
PASSWRD=$(dd if=/dev/urandom count=14 bs=1 | mimencode | cut -c3-18)

# add crontab entry to dump all databases to /srv/backup/mysql.dump
( crontab -l; echo "0 5 * * * /usr/bin/mysqldump -u mysqlbackup -p$PASSWRD -A --add-drop-database --routines --triggers > /srv/backup/mysql.dump" ) | egrep -v "^#" | crontab -

# create mysql backup directory
mkdir -p /srv/backup

# add two users with limited rights for the backup and Nagios checking
( echo "create user 'nagiosuser'@'localhost' identified by 'NidBmT.';"
echo "grant SHOW DATABASES, SELECT on *.* to 'nagiosuser'@'localhost';"
echo "grant REPLICATION CLIENT on *.* to 'nagiosuser'@'localhost';"
echo "grant SHOW DATABASES, SHOW VIEW, SELECT, LOCK TABLES, RELOAD on *.* to 'mysqlbackup'@'localhost' identified by '$PASSWRD';"
echo "flush privileges;" ) | mysql -u root $MPADMINPW
