# Description: The latest stable kernel version
# URL: http://www.kernel.org
# Packagers: milisarge


name=kernel-lts
version=4.4.6
release=1
_version=${version%.*}

source=(http://www.kernel.org/pub/linux/kernel/v4.x/linux-${_version}.tar.xz
	https://www.kernel.org/pub/linux/kernel/v4.x/patch-$version.xz
	$name.config $name.config_64 )

build(){


cd linux-${_version}

if [ -f $SRC/patch-$version.xz ]; then
	xz -d -c  $SRC/patch-$version.xz | patch -Np1
fi

make mrproper
case `uname -m` in
	x86_64)
		cp $SRC/$name.config_64 ./.config;;
	i?86)
		cp $SRC/$name.config ./.config;
esac

# make menuconfig

make || make -j1

case `uname -m` in
        x86_64)
		cp .config $SRC/$name.config_64;;
        i?86)
		cp .config $SRC/$name.config;;
esac

# Install modules
cd $SRC/linux-${_version}
sed -i "/rm\ -rf\ \$(MODLIB)\/kernel/d" Makefile
make INSTALL_MOD_PATH=$PKG modules_install || make -j1 INSTALL_MOD_PATH=$PKG modules_install
mkdir -p $PKG/boot
case `uname -m` in
        x86_64)
                cp  System.map \
                $PKG/boot/System_64.map-$version
                cp  .config    \
                $PKG/boot/config_64-$version
                cp  arch/x86_64/boot/bzImage \
                $PKG/boot/$name-$version ;;
        i?86)
                cp  System.map \
                $PKG/boot/System.map-$version
                cp  .config \
                $PKG/boot/config-$version
                cp  arch/i386/boot/bzImage \
                $PKG/boot/$name-$version ;;
esac

cd $PKG/lib/modules/${version}*/

mkdir -p $PKG/usr/src

mv $SRC/linux-${_version} $PKG/usr/src/
rm {build,source}

ln -sv /usr/src/linux-${_version} build
ln -sv /usr/src/linux-${_version} source

mkdir $SRC/linux-${_version}
mv $PKG/usr/src/linux-${_version}/Documentation \
$SRC/linux-${_version}

# Firmware are in linux-firmware
rm -rf $PKG/lib/firmware

# post-install autogen
INITRD_VERSION="`basename $PKG/lib/modules/*`"
echo "mkinitramfs $INITRD_VERSION" > $PKGMK_ROOT/$name.post-install
echo "[ -f boot/initrd ] && rm boot/initrd" >> $PKGMK_ROOT/$name.post-install
echo "ln -sf initrd-$INITRD_VERSION boot/initrd" >> $PKGMK_ROOT/$name.post-install
echo "ln -sf $name-$version boot/kernel" >> $PKGMK_ROOT/$name.post-install

#pre-install autogen
cd $SRC
if [ -f aaabasicfs-${AAABASICFS}.tar.xz ]; then
 bsdtar -p -o -C $SRC -xf aaabasicfs-${AAABASICFS}.tar.xz
 echo ". lib/lsb/init-functions" >  $PKGMK_ROOT/$name.pre-install
 for FILE in `tar --list --file aaabasicfs-${AAABASICFS}.tar.xz|grep -v /$`
 do
   echo "log_info_msg \"update $FILE\"" >> $PKGMK_ROOT/$name.pre-install
   echo "cat  > $FILE << \"END_OF_FILE\"" >> $PKGMK_ROOT/$name.pre-install
   cat $SRC/$FILE >> $PKGMK_ROOT/$name.pre-install
   echo "END_OF_FILE" >> $PKGMK_ROOT/$name.pre-install
   echo "evaluate_retval" >> $PKGMK_ROOT/$name.pre-install
 done
fi
}

rm -r $PKG/usr/src/
