#!/bin/bash
## Kernel-compile script for Debian based Distros, July 2009 - Vers. 0.51
## by dabang http://www.funzt.info/?p=331
## GPL2 licensed
##
## Please see attached README!


## variables (please adjust if necessary)

# PLEASE ADJUST THIS TO YOUR NEEDS, '/usr/src' IS RECOMMENDED:
ksrc_path=/usr/src

# kernel.org URL
korg_url="http://www.kernel.org"

# KERNEL DOWNLOAD URL, PLEASE ADJUST IF NECESSARY:
k_src_url="http://www.kernel.org/pub/linux/kernel/v2.6"

# PATH TO SAMPLE CONFIG
conf_sample=$ksrc_path/config-sample

# THOSE PACKAGES WILL BE CREATED, ADJUST IF YOU LIKE (see 'man make-kpkg'):
targets="kernel_image kernel_headers kernel_doc kernel_source"

# THIS WILL BE ADDED TO YOUR KERNEL-NAME, I.E. ARCHITECTURE LIKE 'i386'
# AND/OR PROCESSOR TYPE [ONLY LOWERCASE ALPHANUMERICS AND ~ - + . ]:
karch=amd64-k8


#---------------no editing beneath this line necessary-----------------#


## messages

unp_succ="* Successfully created target directories and extracted kernel sources!\n"
unp_fail="* Error! Something went wrong while creating target directories\n and/or extracting kernel source. Aborting now...\n"
comp_succ="\n* Your new kernel seems to have compiled successfully! Debian packages created!\n"
comp_fail="\n* Something went wrong while creating your kernel and/or packages. Aborting...\n"
dir_succ="* Successfully changed working directory to kernel source tree!\n"
dir_fail="* Failed to change directory to kernel source tree... Aborting.\n"


## functions

# check return codes
function check_ret {
	if [ "$1" != "0" ]; then
		echo -e "$2"
		exit 1;
	else
		echo -e "$3"
	fi
}

# kernel configuration
function configuration {
	cd $ksrc_path/$k_vers/linux-$k_vers
	check_ret $? "$dir_fail" "$dir_succ"
	if [ -f $ksrc_path/$k_vers/linux-$k_vers/.config ]; then
		echo -e "* Using existing '.config'...\n"
	else
		echo -e "* Applying sample .config and running 'make oldconfig'...\n"
		cp $conf_sample $ksrc_path/$k_vers/linux-$k_vers/.config && make oldconfig
	fi
	echo ""
	echo -e "* Run 'make xconfig' now? [y/n]"
	read answer1
	echo ""
	case "$answer1" in
		"Y" | "y" )
			echo -e "* Starting 'make xconfig' now...\n"
			make xconfig
			;;
		* )
			echo -e "* OK, skipping 'make xconfig'.\n"
			;;
	esac
	echo -e "\n* Finished configuring kernel!\n"
}

# compile/install new kernel
function compile {
	echo -e "* Ready to compile new kernel $k_vers. Begin?\n (This will take a while...) [y/n]"
	read answer2
	case "$answer2" in
		"Y" | "y" )
                        echo -e "\n* Ok, as you wish. You can watch the output here:\n"
                        cd $ksrc_path/$k_vers/linux-$k_vers && make-kpkg clean
			for i in $targets; do
				fakeroot make-kpkg --initrd --append_to_version -$rev-$karch --revision=$k_vers~$rev $i
			done
			check_ret $? "$comp_fail" "$comp_succ"

			echo -e "\n* Now backing up old '$conf_sample'\nand copying current '.config' to '$conf_sample'...\n"
			mv $conf_sample $conf_sample.$(date +%x)-$(date +%X) && cp $ksrc_path/$k_vers/linux-$k_vers/.config $conf_sample
			ret=$?
			if [ "$ret" != "0" ]; then
				echo -e "\n* INFO: Failed backing up old sample '.config' and/or writing new one...\n"
			else
				echo -e "\n* Done!\n"
			fi

			echo -e "\n* Do you want to install your new kernel now?\n (Need root privileges for this!) [y/n]"
			read answer3
			echo ""
			case "$answer3" in
				"Y" | "y" )
					echo -e "* Installing new kernel packages...\n"
					su -c "dpkg -i ../linux-image-$k_vers-$rev*.deb && dpkg -i ../linux-headers-$k_vers-$rev*.deb"
					
					if [ -f /boot/initrd.img-$k_vers-$rev-$karch ]; then
						echo -e "* Removing initrd and creating new one... (Need root privileges again!)\n"
						su -c "update-initramfs -d -k $k_vers-$rev-$karch && update-initramfs -c -k $k_vers-$rev-$karch && update-grub"
					else
						echo -e "* initrd does not exist, creating one now... (Need root privileges again!)\n"
						su -c "update-initramfs -c -k $k_vers-$rev-$karch && update-grub"
					fi
					
					echo ""
					echo -e "* New kernel seems to be installed! Please take care of any proprietary\n driver (i.e. Nvidia/Ati) yourself!\n"
					;;
				* )
					echo -e "* OK, leaving system as it is.\n"
					exit 0;
					;;
			esac
			;;
		* )
			echo -e "* Quitting now...\n"
			exit 1;
			;;
	esac
}

# download kernel sources
function dl_ksrc {
	echo -e "\n* Trying to download 'linux-$k_vers.tar.bz2' from kernel.org\n to $ksrc_path\n"
	cd $ksrc_path
	wget $k_src_url/linux-$k_vers.tar.bz2 && wget $k_src_url/linux-$k_vers.tar.bz2.sign
	echo -e "\n* Checking gpg signature..."
	gpg --verify linux-$k_vers.tar.bz2.sign 1>/dev/null 2>&1
	ret_gpg_check=$?
	if [ "$ret_gpg_check" != "0" ]; then
		echo -e "\n* Signature verification failed!! Please check!! Aborting now...\n"
		exit 1;
	else
		echo -e "\n* The gpg signature seems to be valid. Continuing now.\n"
		echo -e "* Creating directory '$k_vers' and extracting kernel sources."
		echo -e "* Please wait..."
		(mkdir $k_vers && cd $ksrc_path/$k_vers && tar xvf ../linux-$k_vers.tar.bz2) 1>/dev/null 2>&1
		check_ret $? "$unp_fail" "$unp_succ"
	fi
}

# configure kernel package name/version
function params {
	echo -e "* Please submit desired revision (i.e. 'custom0.1')\n [only alphanumerics and ~ + .]:"
	read rev
	echo ""
	echo "* Please check parameters:"
	echo "--------------------------"
	echo " Kernel source path: $ksrc_path/$k_vers/linux-$k_vers"
	echo " Kernel version: $k_vers"
	echo " Debian package: linux-image-${k_vers}-${rev}-${karch}_${k_vers}~${rev}_[ARCH].deb"
	echo " Revision: $rev"
	echo ""
	echo -e "* Is this correct? [y/n]"
	read answer
	echo ""
	case "$answer" in
		"Y" | "y" )
			if [ -d $ksrc_path/$k_vers/linux-$k_vers ]; then
				echo -e "* OK, starting with process..."
				configuration && compile			
			else
				echo -e "* Creating directory '$k_vers' and extracting kernel sources...\n"
				echo -e "* Please wait..."
				(mkdir $ksrc_path/$k_vers && cd $ksrc_path/$k_vers && tar xvf ../linux-$k_vers.tar.bz2) 1>/dev/null 2>&1
				check_ret $? "$unp_fail" "$unp_succ"
				echo -e "* OK, starting with process..."
				configuration && compile
			fi
			;;
		* )
			echo -e "* Aborting. Please re-run this script with correct parameters.\n"
			exit 1;
			;;
	esac
}

# check for latest kernel version
function check_k_vers {
	echo -e "* Check for latest kernel version on kernel.org? [y/n]"
	read answer
	echo ""
	case "$answer" in
		"Y" | "y" )
			echo -e "* Connecting to kernel.org...\n"
			wget -O /tmp/kernel.org.html_tmp $korg_url 1>/dev/null 2>&1
			latest_k=$(grep -A 6 "Latest Stable Kernel:" /tmp/kernel.org.html_tmp | tail -1 | cut -d "-" -f 2 | sed 's/.tar.bz2\">//g')
			echo -e "* The latest kernel version seems to be: $latest_k\n"
			rm /tmp/kernel.org.html_tmp 1>/dev/null 2>&1
			;;
		* )
			echo -e "* OK, continuing...\n"
			;;
	esac
}


## main

echo ""
echo "********************************************************************"
echo "*                                                                  *"
echo "*               Building custom kernel for Debian                  *"
echo "*                             V. 0.51                              *"
echo "*               by dabang (http://www.funzt.info)                  *"
echo "*                           GPL2 licensed                          *"
echo "*                                                                  *"
echo "********************************************************************"
echo ""

echo "INFO: This script will generate custom Debian kernel packages,"
echo "including kernel-header, kernel-doc and kernel-source packages."
echo "Have fun!"
echo ""
check_k_vers
echo -e "* Please submit desired kernel version (i.e. '2.6.27.5'):"
read k_vers
echo ""
if [ -f $ksrc_path/linux-$k_vers.tar.bz2 ];  then
	echo -e "* Using previously dowloaded kernel source $k_vers...\n"
	params
else
	echo "* Sorry, couldn't find kernel sources. Do you want me to download"
	echo -e "* the kernel sources for kernel $k_vers? [y/n]"
	read answer4
	case "$answer4" in
		"Y" | "y" )
			dl_ksrc && params
			;;
		* )
			echo -e "\n* Aborting...\n"
			exit 1;
			;;
	esac
	echo ""
fi
