# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

inherit linux-mod eutils

SRC_URI="http://easynews.dl.sourceforge.net/sourceforge/${PN}/${P}.tar.gz"

DESCRIPTION="KVM (for Kernel-based Virtual Machine) is a full virtualization solution for Linux on x86 hardware containing virtualization extensions (Intel VT or AMD-V)"
HOMEPAGE="http://kvm.qumranet.com/kvmwiki"

LICENSE="GPL-2"
SLOT="0"
KEYWORDS="~x86 ~amd64"
IUSE=""

MODULE_NAMES="kernel/kvm(extra:)
	      kernel/kvm-intel(extra:)
	      kernel/kvm-amd(extra:)"
BUILD_TARGETS="kernel"

pkg_setup() {
	if [ "$(gcc-major-version)" == "4" ]; then
	eerror "kvm requires gcc-3 in order to build and work correctly"
	eerror "please compile it switching to gcc-3."
	die "gcc 4 cannot build qemu"
	fi
	#>=kvm-13 doesn't work with modules from linux kernel 2.6.20 
	if kernel_is 2 6 20 && linux_chkconfig_builtin KVM ; then
		eerror "kvm-${PV} doesn't work with the 2.6.20 kernel module"
		die "kvm module is included in the 2.6.20 kernel"
	fi

}

src_unpack() {
	unpack ${A}
	cd "${S}"

	epatch ${FILESDIR}/kvm_use_bios_files_in_usr_share_kvm-15.patch
	epatch ${FILESDIR}/kvm_use_etc_kvm_kvm-ifup-15.patch
}

src_compile() {
	#fix make install to not install modules
	sed -i '/$(kcmd)/d' ${WORKDIR}/${P}/Makefile

	linux-mod_pkg_setup	
	conf_opts="--prefix=/usr"

	#Check if kvm is NOT part of the kernel and compile the module
	if ! linux_chkconfig_builtin KVM ; then
		./configure ${conf_opts} || die "Configure failed"
		linux-mod_src_compile
	#If it is we need to disable the build of the module
	else
		./configure ${conf_opts} --with-patched-kernel || die "Configure failed"
	fi
	emake user qemu || die "make failed"
}

src_install() {
	make install DESTDIR="${D}" || die
	if ! linux_chkconfig_builtin KVM; then
		linux-mod_src_install
	fi
	if use amd64; then
        	mv ${D}/usr/bin/qemu-system-x86_64 ${D}/usr/bin/kvm
        else
                mv ${D}/usr/bin/qemu ${D}/usr/bin/kvm
	fi
	mv ${D}/usr/share/doc/qemu ${D}/usr/share/doc/kvm
	mv ${D}/usr/share/man/man1/qemu.1 ${D}/usr/share/man/man1/kvm.1
	rm -f ${D}/usr/bin/qemu-img
	rm -f ${D}/usr/share/man/man1/qemu-img.1
	insinto /etc/udev/rules.d/
	doins ${WORKDIR}/${P}/scripts/65-kvm.rules
	insinto /etc/kvm/
	doins ${WORKDIR}/${P}/scripts/qemu-ifup
	
}

pkg_postinst() {
	enewgroup kvm

	elog "qemu-img is removed from this package."
	elog "If you wanna use it. Install qemu."
	elog "Make sure you have the kernel module loaded before running kvm"
        elog "and your user is in the 'kvm' group"
	elog "Just run 'gpasswd -a <USER> kvm', then have <USER> re-login."

}