# Copyright 1999-2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

EAPI=2

KEYWORDS="~amd64 ~x86"

WANT_AUTOCONF="latest"
WANT_AUTOMAKE="latest"

inherit eutils flag-o-matic gnuconfig autotools versionator toolchain-funcs

MY_PKG="Percona-Server"
MY_VER="5.1.58"
SRC_URI="http://www.percona.com/redir/downloads/Percona-Server-5.1/Percona-Server-5.1.58-12.9/source/${MY_PKG}-${MY_VER}.tar.gz"
S=${WORKDIR}/${MY_PKG}-${MY_VER}/

DESCRIPTION="A fast, multi-threaded, multi-user SQL database server."
HOMEPAGE="http://www.percona.com/"
LICENSE="GPL-2"
SLOT="0"
IUSE="+ssl static debug example latin1"

# Be warned, *DEPEND are version-dependant
# These are used for both runtime and compiletime
DEPEND="ssl? ( >=dev-libs/openssl-0.9.6d )
        userland_GNU? ( sys-process/procps )
		>=dev-db/mysql-init-scripts-1.1
        >=sys-apps/sed-4
        >=sys-apps/texinfo-4.7-r1
        >=sys-libs/readline-4.1
		>=dev-libs/libevent-1.4
        >=sys-libs/zlib-1.2.3"

# Having different flavours at the same time is not a good idea
for i in "mysql" "mysql-community" "mysql-cluster" "mariadb" ; do
	[[ "${i}" == ${PN} ]] ||
	DEPEND="${DEPEND} !dev-db/${i}"
done

RDEPEND="${DEPEND}
		=virtual/mysql-5.1"

# @FUNCTION: mysql_init_vars
# @DESCRIPTION:
# void mysql_init_vars()
# Initialize global variables
# 2005-11-19 <vivo@gentoo.org>
mysql_init_vars() {
	MY_SHAREDSTATEDIR=${MY_SHAREDSTATEDIR="/usr/share/mysql"}
	MY_SYSCONFDIR=${MY_SYSCONFDIR="/etc/mysql"}
	MY_LIBDIR=${MY_LIBDIR="/usr/$(get_libdir)/mysql"}
	MY_LOCALSTATEDIR=${MY_LOCALSTATEDIR="/var/lib/mysql"}
	MY_LOGDIR=${MY_LOGDIR="/var/log/mysql"}
	MY_INCLUDEDIR=${MY_INCLUDEDIR="/usr/include/mysql"}

	if [[ -z "${MY_DATADIR}" ]] ; then
		MY_DATADIR=""
		if [[ -f "${MY_SYSCONFDIR}/my.cnf" ]] ; then
			MY_DATADIR=`"my_print_defaults" mysqld 2>/dev/null \
				| sed -ne '/datadir/s|^--datadir=||p' \
				| tail -n1`
			if [[ -z "${MY_DATADIR}" ]] ; then
				MY_DATADIR=`grep ^datadir "${MY_SYSCONFDIR}/my.cnf" \
				| sed -e 's/.*=\s*//' \
				| tail -n1`
			fi
		fi
		if [[ -z "${MY_DATADIR}" ]] ; then
			MY_DATADIR="${MY_LOCALSTATEDIR}"
			einfo "Using default MY_DATADIR"
		fi
		elog "MySQL MY_DATADIR is ${MY_DATADIR}"

		if [[ -z "${PREVIOUS_DATADIR}" ]] ; then
			if [[ -e "${MY_DATADIR}" ]] ; then
				# If you get this and you're wondering about it, see bug #207636
				elog "MySQL datadir found in ${MY_DATADIR}"
				elog "A new one will not be created."
				PREVIOUS_DATADIR="yes"
			else
				PREVIOUS_DATADIR="no"
			fi
			export PREVIOUS_DATADIR
		fi
	else
		if [[ ${EBUILD_PHASE} == "config" ]]; then
			local new_MY_DATADIR
			new_MY_DATADIR=`"my_print_defaults" mysqld 2>/dev/null \
				| sed -ne '/datadir/s|^--datadir=||p' \
				| tail -n1`

			if [[ ( -n "${new_MY_DATADIR}" ) && ( "${new_MY_DATADIR}" != "${MY_DATADIR}" ) ]]; then
				ewarn "MySQL MY_DATADIR has changed"
				ewarn "from ${MY_DATADIR}"
				ewarn "to ${new_MY_DATADIR}"
				MY_DATADIR="${new_MY_DATADIR}"
			fi
		fi
	fi


	export MY_SHAREDSTATEDIR MY_SYSCONFDIR
	export MY_LIBDIR MY_LOCALSTATEDIR MY_LOGDIR
	export MY_INCLUDEDIR MY_DATADIR MY_SOURCEDIR
}

mysql_lib_symlinks() {
	einfo "Updating MySQL .so symlinks"
	local d dirlist maxdots soname sonameln reldir
	reldir="${1}"
	pushd "${reldir}/usr/$(get_libdir)" &> /dev/null
	# dirlist must contain the less significative directory left
	dirlist="mysql"

	# waste some time in removing and recreating symlinks
	for d in $dirlist ; do
	for soname in $( find "${d}" -name "*.so*" -and -not -type "l" 2>/dev/null ) ; do
	# maxdot is a limit versus infinite loop
	maxdots=0
	sonameln=${soname##*/}
	# loop in version of the library to link it, similar to how
	# libtool works
	while [[ ${sonameln:0-3} != '.so' ]] && [[ ${maxdots} -lt 6 ]] ; do
	rm -f "${sonameln}"
	ln -s "${soname}" "${sonameln}"
	(( ++maxdots ))
	sonameln="${sonameln%.*}"
	done
	rm -f "${sonameln}"
	ln -s "${soname}" "${sonameln}"
		done
	done
	popd &> /dev/null
}

configure_common() {
	myconf="${myconf} --enable-local-infile"
	myconf="${myconf} --with-extra-charsets=all"
	myconf="${myconf} --with-mysqld-user=mysql"
	myconf="${myconf} --with-unix-socket-path=/var/run/mysqld/mysqld.sock"
	myconf="${myconf} --with-fast-mutexes"
	myconf="${myconf} --with-plugin-myisam"
	myconf="${myconf} --with-plugin-myisammrg"
	myconf="${myconf} --with-plugin-partition"
	myconf="${myconf} --with-plugin-archive"
	myconf="${myconf} --with-plugin-blackhole"
	myconf="${myconf} --with-plugin-innodb_plugin"
	myconf="${myconf} --with-plugin-blackhole"
	myconf="${myconf} --with-plugin-csv"
	myconf="${myconf} --with-plugin-example"
	myconf="${myconf} --with-plugin-federated"
	myconf="${myconf} --with-plugin-heap"
	myconf="${myconf} --with-plugin-innobase"


	if use static ; then
		myconf="${myconf} --with-mysqld-ldflags=-all-static"
		myconf="${myconf} --with-client-ldflags=-all-static"
		myconf="${myconf} --disable-shared --with-pic"
	else
		myconf="${myconf} --enable-shared --enable-static"
	fi

	if use debug ; then
		 myconf="${myconf} --with-debug=full"
	else
		myconf="${myconf} --without-debug"
	fi



	if [ -n "${MYSQL_DEFAULT_CHARSET}" -a -n "${MYSQL_DEFAULT_COLLATION}" ]; then
		ewarn "You are using a custom charset of ${MYSQL_DEFAULT_CHARSET}"
		ewarn "and a collation of ${MYSQL_DEFAULT_COLLATION}."
		ewarn "You MUST file bugs without these variables set."
		myconf="${myconf} --with-charset=${MYSQL_DEFAULT_CHARSET}"
		myconf="${myconf} --with-collation=${MYSQL_DEFAULT_COLLATION}"
	elif ! use latin1 ; then
		myconf="${myconf} --with-charset=utf8"
	myconf="${myconf} --with-collation=utf8_general_ci"
	else
	myconf="${myconf} --with-charset=latin1"
	myconf="${myconf} --with-collation=latin1_swedish_ci"
	fi
}

pkg_setup() {
	    enewgroup mysql 60 || die "problem adding 'mysql' group"
		enewuser mysql 60 -1 /dev/null mysql || die "problem adding 'mysql' user"
}

src_prepare() {
	cd "${S}"

}

src_configure() { 
	# Make sure the vars are correctly initialized
	mysql_init_vars
	configure_common

	# Bug #114895, bug #110149
	filter-flags "-O" "-O[01]"

	# glib-2.3.2_pre fix, bug #16496
	append-flags "-DHAVE_ERRNO_AS_DEFINE=1"

	# As discovered by bug #246652, doing a double-level of SSP causes NDB to
	# fail badly during cluster startup.
	if [[ $(gcc-major-version) -lt 4 ]]; then
		filter-flags "-fstack-protector-all"
	fi

	CXXFLAGS="${CXXFLAGS} -fno-exceptions -fno-strict-aliasing"
	CXXFLAGS="${CXXFLAGS} -felide-constructors -fno-rtti"
	CXXFLAGS="${CXXFLAGS} -fno-implicit-templates"
	export CXXFLAGS

	# bug #283926, with GCC4.4, this is required to get correct behavior.
	append-flags -fno-strict-aliasing

	# bug #335185, #335995, with >= GCC4.3.3 on x86 only, omit-frame-pointer
	# causes a mis-compile.
	# Upstream bugs:
	# http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38562
	# http://bugs.mysql.com/bug.php?id=45205
	use x86 && version_is_at_least "4.3.3" "$(gcc-fullversion)" && \
		append-flags -fno-omit-frame-pointer && \
		filter-flags -fomit-frame-pointer

	econf \
		--libexecdir="/usr/sbin" \
		--sysconfdir="${MY_SYSCONFDIR}" \
		--localstatedir="${MY_LOCALSTATEDIR}" \
		--sharedstatedir="${MY_SHAREDSTATEDIR}" \
		--libdir="${MY_LIBDIR}" \
		--includedir="${MY_INCLUDEDIR}" \
		--with-low-memory \
		--with-client-ldflags=-lstdc++ \
		--enable-thread-safe-client \
		--with-comment="Gentoo Linux ${PF}" \
		--without-docs \
		${myconf} || die "econf failed"

	# TODO: Move this before autoreconf !!!
	find . -type f -name Makefile -print0 \
	| xargs -0 -n100 sed -i \
	-e 's|^pkglibdir *= *$(libdir)/mysql|pkglibdir = $(libdir)|;s|^pkgincludedir *= *$(includedir)/mysql|pkgincludedir = $(includedir)|'

}

src_compile() {
	# Be backwards compatible for now
	case ${EAPI:-0} in
		2) : ;;
		0 | 1) src_configure ;;
	esac

	emake || die "emake failed"

}

src_install() {
	# Make sure the vars are correctly initialized
	mysql_init_vars

	emake install \
		DESTDIR="${D}" \
		benchdir_root="${MY_SHAREDSTATEDIR}" \
		testroot="${MY_SHAREDSTATEDIR}" \
		|| die "emake install failed"

	# Convenience links
	einfo "Making Convenience links for mysqlcheck multi-call binary"
	dosym "/usr/bin/mysqlcheck" "/usr/bin/mysqlanalyze"
	dosym "/usr/bin/mysqlcheck" "/usr/bin/mysqlrepair"
	dosym "/usr/bin/mysqlcheck" "/usr/bin/mysqloptimize"

	# Various junk (my-*.cnf moved elsewhere)
	einfo "Removing duplicate /usr/share/mysql files"
	rm -Rf "${D}/usr/share/info"
	for removeme in  "mysql-log-rotate" mysql.server* \
		binary-configure* my-*.cnf mi_test_all*
	do
		rm -f "${D}"/${MY_SHAREDSTATEDIR}/${removeme}
	done

	# Clean up stuff for a minimal build
	# Unless they explicitly specific USE=test, then do not install the
	# testsuite. It DOES have a use to be installed, esp. when you want to do a
	# validation of your database configuration after tuning it.
	if use !test ; then
		rm -rf "${D}"/${MY_SHAREDSTATEDIR}/mysql-test
	fi

	#einfo "Building default my.cnf (${mysql_mycnf_version})"
	#einfo "Building default my.cnf"
	insinto "${MY_SYSCONFDIR}"
	doins scripts/mysqlaccess.conf
	#mycnf_src="${FILESDIR}/my.cnf"
	#mycnf_src="${PORTDIR_OVERLAY}/${CATEGORY}/${PN}/files/my.cnf"
	sed -e "s!@DATADIR@!${MY_DATADIR}!g" \
		"${FILESDIR}/my.cnf" \
		> "${TMPDIR}/my.cnf.ok"
	if use latin1 ; then
		sed -i \
			-e "/character-set/s|utf8|latin1|g" \
			"${TMPDIR}/my.cnf.ok"
	fi
	newins "${TMPDIR}/my.cnf.ok" my.cnf

		einfo "Creating initial directories"
		# Empty directories ...
		diropts "-m0750"
		if [[ "${PREVIOUS_DATADIR}" != "yes" ]] ; then
			dodir "${MY_DATADIR}"
			keepdir "${MY_DATADIR}"
			chown -R mysql:mysql "${D}/${MY_DATADIR}"
		fi

		diropts "-m0755"
		for folder in "${MY_LOGDIR}" "/var/run/mysqld" ; do
			dodir "${folder}"
			keepdir "${folder}"
			chown -R mysql:mysql "${D}/${folder}"
		done

	# Docs
	einfo "Installing docs"
	dodoc README ChangeLog INSTALL-SOURCE
	doinfo "${S}"/Docs/mysql.info

		einfo "Including support files and sample configurations"
		docinto "support-files"
		for script in \
			"${S}"/support-files/my-*.cnf \
			"${S}"/support-files/magic \
			"${S}"/support-files/ndb-config-2-node.ini
		do
			[[ -f "$script" ]] && dodoc "${script}"
		done

		docinto "scripts"
		for script in "${S}"/scripts/mysql* ; do
			[[ -f "$script" ]] && [[ "${script%.sh}" == "${script}" ]] && dodoc "${script}"
		done

		mysql_lib_symlinks "${D}"
}

pkg_preinst() {
	enewgroup mysql 60 || die "problem adding 'mysql' group"
	enewuser mysql 60 -1 /dev/null mysql || die "problem adding 'mysql' user"
}

pkg_postinst() {
	# Make sure the vars are correctly initialized
	mysql_init_vars

	# Check FEATURES="collision-protect" before removing this
	[[ -d "${ROOT}/var/log/mysql" ]] || install -d -m0750 -o mysql -g mysql "${ROOT}${MY_LOGDIR}"

	# Secure the logfiles
	touch "${ROOT}${MY_LOGDIR}"/mysql.{log,err}
	chown mysql:mysql "${ROOT}${MY_LOGDIR}"/mysql*
	chmod 0660 "${ROOT}${MY_LOGDIR}"/mysql*

	# Minimal builds don't have the MySQL server
		docinto "support-files"
		for script in \
			support-files/my-*.cnf \
			support-files/magic \
			support-files/ndb-config-2-node.ini
		do
			[[ -f "${script}" ]] \
			&& dodoc "${script}"
		done

		docinto "scripts"
		for script in scripts/mysql* ; do
			[[ -f "${script}" ]] \
			&& [[ "${script%.sh}" == "${script}" ]] \
			&& dodoc "${script}"
		done

		einfo
		elog "You might want to run:"
		elog "mysql_install_db"
		elog "if this is a new install."
		einfo

		einfo
		elog "Afterwards it would be a good idea to issue the command"
		elog "mysql_secure_installation"
		einfo

		einfo
		elog "If you are upgrading major versions, you should run the"
		elog "mysql_upgrade tool."
		einfo

}

pkg_postrm() {
	:	# mysql_lib_symlinks "${D}"
}