#!/bin/bash -e

. /usr/share/debconf/confmodule

if [ -n "$DEBIAN_SCRIPT_DEBUG" ]; then set -v -x; DEBIAN_SCRIPT_TRACE=1; fi
${DEBIAN_SCRIPT_TRACE:+ echo "#42#DEBUG# RUNNING $0 $*" 1>&2 }

export PATH=$PATH:/sbin:/usr/sbin:/bin:/usr/bin

# This command can be used as pipe to syslog. With "-s" it also logs to stderr.
ERR_LOGGER="logger -p daemon.err -t mysqld_safe -i"
# This will make an error in a logged command immediately apparent by aborting
# the install, rather than failing silently and leaving a broken install.
set -o pipefail

invoke() {
  if [ -x /usr/sbin/invoke-rc.d ]; then
    invoke-rc.d mysql $1
  else
    /etc/init.d/mysql $1
  fi
}

MYSQL_BOOTSTRAP="/usr/sbin/mysqld --bootstrap --user=mysql --disable-log-bin --skip-grant-tables --default-storage-engine=myisam"

set_mysql_rootpw() {
       # forget we ever saw the password.  don't use reset to keep the seen status
       db_set mysql-server/root_password ""
       db_set mysql-server/root_password_again ""

       tfile=`mktemp`
       if [ ! -f "$tfile" ]; then
               return 1
       fi

       # this avoids us having to call "test" or "[" on $rootpw
       cat << EOF > $tfile
USE mysql;
SET sql_log_bin=0;
UPDATE user SET password=PASSWORD("$rootpw") WHERE user='root';
FLUSH PRIVILEGES;
EOF
       if grep -q 'PASSWORD("")' $tfile; then
               retval=0
       else
               $MYSQL_BOOTSTRAP <$tfile
               retval=$?
       fi
       rm -f $tfile
       return $retval
}

case "$1" in
  configure)
    # This is needed because mysql_install_db removes the pid file in /var/run
    # and because changed configuration options should take effect immediately.
    # In case the server wasn't running at all it should be ok if the stop
    # script fails. I can't tell at this point because of the cleaned /var/run.
    set +e; invoke stop; set -e

    mysql_statedir=/usr/share/mysql
    mysql_datadir=/var/lib/mysql
    mysql_logdir=/var/log/mysql
    mysql_rundir=/var/run/mysqld
    mysql_cfgdir=/etc/mysql
    mysql_upgradedir=/var/lib/mysql-upgrade

    # If the following symlink exists, it is a preserved copy the old data dir
    # created by the preinst script during a upgrade that would have otherwise
    # been replaced by an empty mysql dir.  This should restore it.
    for dir in DATADIR LOGDIR; do

      if [ "$dir" = "DATADIR" ]; then
        targetdir=$mysql_datadir
      else
        targetdir=$mysql_logdir
      fi

      savelink="$mysql_upgradedir/$dir.link"
      if [ -L "$savelink" ]; then
        # If the targetdir was a symlink before we upgraded it is supposed
        # to be either still be present or not existing anymore now.
        if [ -L "$targetdir" ]; then
          rm "$savelink"
        elif [ ! -d "$targetdir" ]; then
          mv "$savelink" "$targetdir"
        else
          # this should never even happen, but just in case...
          mysql_tmp=`mktemp -d -t mysql-symlink-restore-XXXXXX`
          echo "this is very strange!  see $mysql_tmp/README..." >&2
          mv "$targetdir" "$mysql_tmp"
          cat << EOF > "$mysql_tmp/README"

If you're reading this, it's most likely because you had replaced /var/lib/mysql
with a symlink, then upgraded to a new version of mysql, and then dpkg
removed your symlink (see #182747 and others). The mysql packages noticed
that this happened, and as a workaround have restored it. However, because
/var/lib/mysql seems to have been re-created in the meantime, and because
we don't want to rm -rf something we don't know as much about, we are going
to leave this unexpected directory here. If your database looks normal,
and this is not a symlink to your database, you should be able to blow
this all away.

EOF
        fi
      fi
	    rmdir $mysql_upgradedir 2>/dev/null || true

    done

    # Ensure the existence and right permissions for the database and
    # log files.
    if [ ! -d "$mysql_statedir" -a ! -L "$mysql_statedir" ]; then mkdir "$mysql_statedir"; fi
    if [ ! -d "$mysql_datadir"  -a ! -L "$mysql_datadir" ]; then mkdir "$mysql_datadir" ; fi
    if [ ! -d "$mysql_logdir"   -a ! -L "$mysql_logdir"  ]; then mkdir "$mysql_logdir"  ; fi
    # When creating an ext3 jounal on an already mounted filesystem like e.g.
    # /var/lib/mysql, you get a .journal file that is not modifyable by chown.
    # The mysql_statedir must not be writable by the mysql user under any
    # circumstances as it contains scripts that are executed by root.
    set +e
    chown -R 0:0 $mysql_statedir
    find $mysql_datadir ! -uid $(id -u mysql) -print0 | xargs -0 -r chown mysql
    chown -R mysql:adm $mysql_logdir
    chmod 2750 $mysql_logdir
    set -e

    # This is important to avoid dataloss when there is a removed
    # mysql-server version from Woody lying around which used the same
    # data directory and then somewhen gets purged by the admin.
    db_set mariadb-server/postrm_remove_database false || true

    # Clean up old flags before setting new one
    rm -f $mysql_datadir/debian-*.flag
    # Flag data dir to avoid downgrades
    touch $mysql_datadir/debian-10.4.flag

    # initiate databases. Output is not allowed by debconf :-(
    # This will fail if we are upgrading an existing database; in this case
    # mysql_upgrade, called from the /etc/init.d/mysql start script, will
    # handle things.
    # Debian: beware of the bashisms...
    # Debian: can safely run on upgrades with existing databases
    set +e
    bash /usr/bin/mysql_install_db --rpm --cross-bootstrap --user=mysql \
                                   --disable-log-bin --skip-test-db 2>&1 | \
                                   $ERR_LOGGER
    set -e


    ## On every reconfiguration the maintenance user is recreated.
    #
    # - It is easier to regenerate the password every time but as people
    #   use fancy rsync scripts and file alteration monitors, the existing
    #   password is used and existing files not touched.
    # - The mysqld statement is like that in mysql_install_db because the
    #   server is not already running. This has some implications:
    # 	- The amount of newlines and semicolons in the query is important!
    #   - GRANT is not possible with --skip-grant-tables and "INSERT
    #     (user,host..) VALUES" is not --ansi compliant
    # - The echo is just for readability. ash's buildin has no "-e" so use /bin/echo.
    # - The Super_priv, Show_db_priv, Create_tmp_table_priv and Lock_tables_priv
    #   may not be present as old Woody 3.23 databases did not have it and the
    #   admin might not already have run mysql_upgrade which adds them.
    #   As the binlog cron scripts to need at least the Super_priv, I do first
    #   the old query which always succeeds and then the new which may or may not.

    # recreate the credentials file if not present or without mysql_upgrade stanza
    dc=$mysql_cfgdir/debian.cnf;
    if [ -e "$dc" -a -n "`fgrep mysql_upgrade $dc 2>/dev/null`" ]; then
        pass="`sed -n 's/^[     ]*password *= *// p' $dc | head -n 1`"
    else
	pass=`perl -e 'print map{("a".."z","A".."Z",0..9)[int(rand(62))]}(1..16)'`;
        if [ ! -d "$mysql_cfgdir" ]; then install -o 0 -g 0 -m 0755 -d $mysql_cfgdir; fi
        umask 066
        cat /dev/null > $dc
        umask 022
        echo "# Automatically generated for Debian scripts. DO NOT TOUCH!" >>$dc
        echo "[client]"                                                    >>$dc
        echo "host     = localhost"                                        >>$dc
        echo "user     = debian-sys-maint"                                 >>$dc
        echo "password = $pass"                                            >>$dc
        echo "socket   = $mysql_rundir/mysqld.sock"                        >>$dc
        echo "[mysql_upgrade]"                                             >>$dc
        echo "host     = localhost"                                        >>$dc
        echo "user     = debian-sys-maint"                                 >>$dc
        echo "password = $pass"                                            >>$dc
        echo "socket   = $mysql_rundir/mysqld.sock"                        >>$dc
        echo "basedir  = /usr"                                             >>$dc
    fi
    # If this dir chmod go+w then the admin did it. But this file should not.
    chown 0:0 $dc
    chmod 0600 $dc

    replace_query=`/bin/echo -e \
        "USE mysql;\n" \
        "SET sql_mode='';\n" \
        "REPLACE INTO user SET " \
        "  host='localhost', user='debian-sys-maint', password=password('$pass'), " \
        "  Select_priv='Y', Insert_priv='Y', Update_priv='Y', Delete_priv='Y', " \
        "  Create_priv='Y', Drop_priv='Y', Reload_priv='Y', Shutdown_priv='Y', " \
        "  Process_priv='Y',  File_priv='Y', Grant_priv='Y', References_priv='Y', " \
        "  Index_priv='Y', Alter_priv='Y', Super_priv='Y', Show_db_priv='Y', "\
        "  Create_tmp_table_priv='Y', Lock_tables_priv='Y', Execute_priv='Y', "\
        "  Repl_slave_priv='Y', Repl_client_priv='Y', Create_view_priv='Y', "\
        "  Show_view_priv='Y', Create_routine_priv='Y', Alter_routine_priv='Y', "\
        "  Create_user_priv='Y', Event_priv='Y', Trigger_priv='Y',"\
        "  ssl_cipher='', x509_issuer='', x509_subject='';"`;

    db_get mysql-server/root_password && rootpw="$RET"
    if ! set_mysql_rootpw; then
      db_input high mysql-server/error_setting_password || true
      db_go
    fi

    set +e
    echo "$replace_query"                                    | $MYSQL_BOOTSTRAP 2>&1 | $ERR_LOGGER
    set -e

    # If there is a real AppArmor profile, we reload it.
    # If the default empty profile is installed, then we remove any old
    # profile that may be loaded.
    # This allows upgrade from old versions (that have an apparmor profile
    # on by default) to work both to disable a default profile, and to keep
    # any profile installed and maintained by users themselves.
    profile="/etc/apparmor.d/usr.sbin.mysqld"
    if [ -f "$profile" ] && aa-status --enabled 2>/dev/null; then
        if grep -q /usr/sbin/mysqld "$profile" 2>/dev/null ; then
            apparmor_parser -r "$profile" || true
        else
            echo "/usr/sbin/mysqld { }" | apparmor_parser --remove 2>/dev/null || true
	fi
    fi

    # copy out any mysqld_safe settings
    systemd_conf=/etc/systemd/system/mariadb.service.d/migrated-from-my.cnf-settings.conf
    if [ -x /usr/bin/mariadb-service-convert -a ! -f "${systemd_conf}" ]; then
      mkdir -p /etc/systemd/system/mariadb.service.d
      /usr/bin/mariadb-service-convert > "${systemd_conf}"
    fi
  ;;

  abort-upgrade|abort-remove|abort-configure)
  ;;

  triggered)
    if [ -x "$(command -v systemctl)" ]; then
      systemctl daemon-reload
    fi
    invoke restart
  ;;

  *)
    echo "postinst called with unknown argument '$1'" 1>&2
    exit 1
  ;;
esac

db_stop # in case invoke failes

# dh_systemd_start doesn't emit anything since we still ship /etc/init.d/mysql.
# Thus MariaDB server is started via init.d script, which in turn redirects to
# systemctl. If we upgrade from MySQL mysql.service may be masked, which also
# means init.d script is disabled. Unmask mysql service explicitly.
# Check first that the command exists, to avoid emitting any warning messages.
if [ -x "$(command -v deb-systemd-helper)" ]; then
  deb-systemd-helper unmask mysql.service > /dev/null
fi

#DEBHELPER#

exit 0