#!/bin/bash

set -e

case $1 in
  preinst)
    exit 0
    ;;
  postinst)
    if ! getent group mysql 2>&1 > /dev/null; then
      if groupadd -g 40 mysql; then
        echo 'Created group mysql'
      else
        echo 'Failed to create group mysql!'
        exit 1
      fi
    fi

    if ! getent passwd mysql 2>&1 > /dev/null; then
      if useradd -c 'MySQL Server' -d /var/lib/mysql -g mysql \
      -s /bin/false -u 40 mysql; then
        echo 'Created user mysql'
      else
        echo 'Failed to create user mysql!'
        exit 1
      fi
    fi

    mysql_install_db --basedir=/usr --datadir=/var/lib/mysql \
	--user=mysql 2>/dev/null
    chown -R mysql:mysql /var/lib/mysql /var/run/mysqld
    ;;
  prerm)
    exit 0
    ;;
  postrm)
    exit 0
    ;;
esac
