# Copyright 2008, 2009, 2010 Ingmar Vanhassel <ingmar@exherbo.org>
# Copyright 2011-2019 Timo Gurr <tgurr@exherbo.org>
# Distributed under the terms of the GNU General Public License v2

require cmake systemd-service

MYSQL_MAJOR_VERSION=$(ever range 1-2)

# In order to provide a stable code base, MySQL depends on a specific version of Boost.
# Currently only Boost.Geometry headers are used and boost is just required at build time.
BOOST_PV=1.59.0

# Miraculously works for MySQL >= 5.1 till at least 5.6
SPHINX_PV="2.2.9"

SUMMARY="A relational database management system (RDBMS)"
HOMEPAGE="https://www.mysql.com/"
DOWNLOADS="
    mirror://mysql/Downloads/MySQL-$(ever range 1-2)/${PNV}.tar.gz
    mirror://sourceforge/boost/boost_${BOOST_PV//./_}.tar.bz2
    https://downloads.mysql.com/archives/${PN}-$(ever range 1-2)/${PNV}.tar.gz
    sphinx? ( http://sphinxsearch.com/files/sphinx-${SPHINX_PV}-release.tar.gz )
"

REMOTE_IDS="freecode:${PN}"
UPSTREAM_CHANGELOG="
    https://dev.mysql.com/doc/relnotes/mysql/${MYSQL_MAJOR_VERSION}/en/news-$(ever replace_all '-').html [[ lang = [ en ] ]]
"
UPSTREAM_DOCUMENTATION="
    https://dev.mysql.com/doc/refman/${MYSQL_MAJOR_VERSION}/en/index.html                 [[ lang = [ en ] ]]
    https://dev.mysql.com/doc/refman/${MYSQL_MAJOR_VERSION}/en/postinstallation.html      [[ lang = [ en ] note = [ Postinstallation documentation ] ]]
    https://dev.mysql.com/doc/refman/${MYSQL_MAJOR_VERSION}/en/upgrading-downgrading.html [[ lang = [ en ] note = [ Upgrading or downgrading documentation ] ]]
"
UPSTREAM_RELEASE_NOTES="
    https://dev.mysql.com/doc/relnotes/mysql/${MYSQL_MAJOR_VERSION}/en/ [[ lang = [ en ] ]]
"

LICENCES="GPL-2" # with-exceptions
SLOT="0"
MYOPTIONS="
    debug
    embedded-server [[ description = [ The embedded MySQL server library (DEPRECATED and slated for removal) ] ]]
    memcached [[ description = [ Enable using memcached for InnoDb tables (don't know it? Don't enable it.) ] ]]
    sphinx [[ description = [ Add the Sphinx Search Engine with fulltext search support (external engine) ] ]]
    systemd
    tcpd
    ( providers: libressl openssl ) [[ number-selected = exactly-one ]]
"

PLATFORMS="~amd64 ~x86"

DEPENDENCIES="
    build:
        virtual/pkg-config
        systemd? ( sys-apps/systemd )
    build+run:
        group/${PN}
        user/${PN}
        app-admin/eclectic[>=2.0.18] [[ note = [ Split ld-*.path, @TARGET@ substitution ] ]]
        app-arch/lz4
        dev-libs/libaio
        dev-libs/libedit
        dev-libs/protobuf:=[>=2.6.1]
        sys-libs/zlib[>=1.2.11]
        providers:libressl? ( dev-libs/libressl:= )
        providers:openssl? ( dev-libs/openssl )
        tcpd? ( sys-apps/tcp-wrappers )
        !dev-db/mariadb [[
            description = [ MariaDB is a drop-in replacement for MySQL with same binary names ]
            resolution = manual
        ]]
        !dev-db/Percona-Server [[
            description = [ Percona-Server is a drop-in replacement for MySQL with same binary names ]
            resolution = manual
        ]]
    recommendation:
        memcached? ( net/memcached [[ description = [ The option provides the bundled memcached but you might want to use a stand-alone memcached as well ] ]] )
    suggestion:
        app-admin/logrotate [[ description = [ Use logrotate for rotating logs ] ]]
"

DEFAULT_SRC_PREPARE_PATCHES=(
    "${FILES}"/mysql-5.7.29-fix-libressl-support.patch
)

# event_comment
# >= 5.6 needs libevent[>=1.4.12&<2.0] but
# a) we only have 2.0.22 at the time of writing
# b) lots of other stuff needs >=2.0
#
# Options:
#
# 1. Add libevent 1.4.x, imlement the dep as [>=1.4.12&<2.0] and watch the fun
# 2. Us the bundled libevent for MySQL to ensure it's always the right version.
# 3. Add libevent 1.4.x as SLOT=1.4, slot 2.0.x as SLOT=2.0, dep on the 1.4 slot here.
#
# I prefer 3., of course, but I went with 2. for now to be on the safe side.
#
#            dev-libs/libevent[>=1.4.12]

pkg_pretend() {
    # Sanity check when upgrading to a different x.y version of mysql
    if [[ -z ${MYSQL_MAJOR_UPGRADE} ]] && has_version ${CATEGORY}/${PN} && \
        ! has_version ${CATEGORY}/${PN}[=${MYSQL_MAJOR_VERSION}*] ; then
        ewarn "To install a different major version of MySQL, you have to dump/reload your database."
        ewarn "When you've done this, please set 'MYSQL_MAJOR_UPGRADE=YesPlease', to continue the upgrade."
        ewarn "For more information visit:"
        ewarn "http://dev.mysql.com/doc/refman/${MYSQL_MAJOR_VERSION}/en/upgrading.html"
        ewarn "http://dev.mysql.com/doc/refman/${MYSQL_MAJOR_VERSION}/en/downgrading.html"
        die "Dump your databases before doing a major version upgrade of MySQL."
    fi

    if [[ -f "${ROOT}"/etc/tmpfiles.d/${PN}.conf ]] ; then
        ewarn "The configuration file /etc/tmpfiles.d/${PN}.conf has been moved to"
        ewarn "/usr/$(exhost --target)/lib/tmpfiles.d/${PN}.conf and can be safely removed after upgrade"
        ewarn "if you did not make any changes to it."
    fi
}

src_prepare() {
    cmake_src_prepare

    # https://bugs.mysql.com/bug.php?id=72353 (only relevant when using system libevent)
    edo sed \
        -e "s:\(LIBEVENT_LIBRAR\)IES:\1Y:" \
        -i "${WORKBASE}"/${PNV}/cmake/libevent.cmake

    # don't link statically against crypto libs
    edo sed \
        -e '/REVERSE CMAKE_FIND_LIBRARY_SUFFIXES/d' \
        -i "${CMAKE_SOURCE}"/cmake/ssl.cmake

    # disable the automagic LDAP SASL Authentication Plugin (client-side)
    # if added it requires cyrus-sasl -DWITH_SASL:STRING=system and openldap and -DWITH_AUTHENTICATION_LDAP:BOOL=TRUE
    edo sed \
        -e '/ADD_SUBDIRECTORY(authentication_ldap)/d' \
        -i "${CMAKE_SOURCE}"/libmysql/CMakeLists.txt
    edo rm -rf "${WORKBASE}"/${PNV}/libmysql/authentication_ldap

    option sphinx && edo ln -s "${WORKBASE}"/sphinx-${SPHINX_PV}-release/mysqlse "${WORKBASE}"/${PNV}/storage/sphinx
}

src_configure() {
    local cmakeargs=(
        -DBOOST_INCLUDE_DIR:PATH="${WORKBASE}"/boost_${BOOST_PV//./_}
        -DBUILD_CONFIG:STRING=mysql_release
        # The default layout STANDALONE breaks all the scripts.
        -DINSTALL_LAYOUT:STRING="RPM"
        -DCMAKE_DISABLE_FIND_PACKAGE_Git:BOOL=TRUE
        -DCMAKE_INSTALL_PREFIX:PATH=/usr
        -DCOMPILATION_COMMENT:STRING="Exherbo"
        -DDEFAULT_CHARSET:STRING=utf8
        -DDEFAULT_COLLATION:STRING=utf8_general_ci
        -DFEATURE_SET:STRING=community
        -DINSTALL_BINDIR:PATH=$(exhost --target)/bin
        -DINSTALL_DOCDIR:PATH=share/doc/${PNVR}
        -DINSTALL_DOCREADMEDIR:PATH=share/doc/${PNVR}
        -DINSTALL_INCLUDEDIR:PATH=$(exhost --target)/include/mysql
        -DINSTALL_INFODIR:PATH=share/mysql/info
        -DINSTALL_LIBDIR:PATH=$(exhost --target)/lib/mysql
        -DINSTALL_MANDIR:PATH=share/man
        -DINSTALL_MYSQLSHAREDIR:PATH=share/mysql
        # Empty value to not install the mysql-test directory
        -DINSTALL_MYSQLTESTDIR:STRING=
        -DINSTALL_PLUGINDIR:PATH=$(exhost --target)/lib/mysql/plugin
        -DINSTALL_SBINDIR:PATH=$(exhost --target)/bin
        -DINSTALL_SCRIPTDIR:PATH=$(exhost --target)/bin
        -DINSTALL_SHAREDIR:PATH=share
        -DINSTALL_SUPPORTFILESDIR:PATH=share/mysql
        -DMYSQL_DATADIR:PATH=/var/lib/mysql
        -DMYSQL_UNIX_ADDR:PATH=/run/mysqld/mysqld.sock
        -DREPRODUCIBLE_BUILD:BOOL=FALSE
        -DSYSCONFDIR:PATH=/etc/mysql
        -DENABLE_DTRACE:BOOL=FALSE
        -DENABLE_GCOV:BOOL=FALSE
        -DENABLE_GPROF:BOOL=FALSE
        -DENABLED_LOCAL_INFILE:BOOL=TRUE
        -DENABLED_PROFILING:BOOL=TRUE
        -DWITH_ASAN:BOOL=FALSE
        -DWITH_ASAN_SCOPE:BOOL=FALSE
        -DWITH_BOOST:PATH="${WORKBASE}"/boost_${BOOST_PV//./_}
        -DWITH_CLIENT_PROTOCOL_TRACING:BOOL=FALSE
        # Curl is only used with yassl
        -DWITH_CURL:BOOL=FALSE
        -DWITH_EDITLINE:STRING=system
        -DWITH_EXTRA_CHARSETS:STRING=all
        # Search for event_comment in this exlib for the reason for using bundled
        -DWITH_LIBEVENT:STRING=bundled
        -DWITH_LZ4:STRING=system
        -DWITH_MSAN:BOOL=FALSE
        -DWITH_NUMA:BOOL=FALSE
        -DWITH_PROTOBUF:STRING=system
        -DWITH_RAPID:BOOL=FALSE
        -DWITH_SSL:STRING=/usr/$(exhost --target)
        -DWITH_TEST_TRACE_PLUGIN:BOOL=FALSE
        -DWITH_UBSAN:BOOL=FALSE
        -DWITH_UNIT_TESTS:BOOL=TRUE
        -DWITH_VALGRIND:BOOL=FALSE
        -DWITH_ZLIB:STRING=system
        # Default ENGINES for MySQL 5.6 community build (currently == xlarge) minus embedded
        -DWITH_ARCHIVE_STORAGE_ENGINE:BOOL=TRUE
        -DWITH_BLACKHOLE_STORAGE_ENGINE:BOOL=TRUE
        -DWITH_FEDERATED_STORAGE_ENGINE:BOOL=TRUE
        -DWITH_INNOBASE_STORAGE_ENGINE:BOOL=TRUE
    )

    if option debug ; then
        cmakeargs+=(
            -DCMAKE_BUILD_TYPE:STRING=Debug
        )
    else
        cmakeargs+=(
            -DCMAKE_BUILD_TYPE:STRING=Release
        )
    fi

    if option memcached ; then
        cmakeargs+=(
            # Unfortunately, the InnoDb/memcached interface needs libevent 1.4.x
            # as bundled with MySQL or trying to use memcached WILL make MySQL
            # segfault immediately.
            # (Keeping this comment even though the bundled lib is used anyway in
            # order to remember *why* I changed it.)
            -DWITH_LIBEVENT:STRING=bundled
            -DWITH_INNODB_MEMCACHED:BOOL=TRUE
        )
    fi

    if option sphinx ; then
        cmakeargs+=(
            -DWITH_SPHINX_STORAGE_ENGINE:BOOL=TRUE
        )
    fi

    if option systemd ; then
        cmakeargs+=(
            -DWITH_SYSTEMD:BOOL=TRUE
            -DSYSTEMD_PID_DIR:PATH=/run/mysqld
            -DSYSTEMD_SERVICES_DIR:PATH=${SYSTEMDSYSTEMUNITDIR}
            -DSYSTEMD_TMPFILES_DIR:PATH=/usr/$(exhost --target)/lib/tmpfiles.d
        )
    else
        cmakeargs+=(
            -DWITH_SYSTEMD:BOOL=FALSE
        )
    fi

    ecmake \
        "${cmakeargs[@]}" \
        $(cmake_with debug DEBUG)\
        $(cmake_with embedded-server EMBEDDED_SERVER)\
        $(cmake_with tcpd LIBWRAP)
}

src_install() {
    cmake_src_install

    # Remove empty directories
    edo rmdir "${IMAGE}"/usr/share/mysql/info
    ! option debug && edo rmdir "${IMAGE}"/usr/$(exhost --target)/lib/mysql/plugin/debug

    keepdir /etc/mysql

    insinto /etc/mysql
    newins "${FILES}"/mysql-$(ever range 1-2)-my.cnf my.cnf

    hereenvd 46mysql <<EOF
LDPATH=/usr/@TARGET@/lib/mysql
EOF

    insinto /etc/logrotate.d
    newins "${FILES}"/logrotate.mysql mysql

    keepdir /var/lib/mysql-files
    edo chown mysql:mysql "${IMAGE}"/var/lib/mysql-files
    edo chmod 0750 "${IMAGE}"/var/lib/mysql-files
}

pkg_postinst() {
    if option sphinx ; then
        elog "In order to finalise your installation of the Sphinx Search Engine, you must install"
        elog "it in MySQL using the following command as an administrative user:"
        elog ""
        elog "mysql> INSTALL PLUGIN SPHINX SONAME 'ha_sphinx.so';"
        elog ""
    fi

    if option memcached ; then
        elog "In order to finalise your installation of the memcached plugin, you must install"
        elog "it in MySQL using the following command as an administrative user:"
        elog ""
        elog "mysql> install plugin daemon_memcached soname "libmemcached.so";"
        elog ""
    fi
}