#!/bin/bash
set -e

VER=3.8.2
BUILD=1
DST=/usr/src/linux-$VER
PKG=/tmp/kernel-$VER
SRC=$(realpath .)/aufs3-standalone.git/

# how to get aufs and utils:
#  git clone git://aufs.git.sourceforge.net/gitroot/aufs/aufs3-standalone.git aufs3-standalone.git
#  cd aufs3-standalone.git
#  git checkout origin/aufs3.8
#  cd ..
#  git clone git://aufs.git.sourceforge.net/gitroot/aufs/aufs-util.git aufs-util.git
#  cd aufs-util.git
#  git checkout origin/aufs3.0

if [ ! -r linux-$VER.tar.xz ]; then
   wget -c http://www.kernel.org/pub/linux/kernel/v3.0/linux-$VER.tar.xz
fi

tar -xf additions.tar.gz

# Automatically determine the architecture we're building on:
if [ -z "$MYARCH" ]; then
  case "$( uname -m )" in
    i?86) export MYARCH=i486 ;;
    arm*) export MYARCH=arm ;;
    # Unless $MYARCH is already set, use uname -m for all other archs:
       *) export MYARCH=$( uname -m ) ;;
  esac
fi

rm -Rf $PKG
umount $DST 2>/dev/null | true
rm -Rf $DST
mkdir -p $DST
#mount -t tmpfs -o size="100%" tmpfs $DST
cd $DST

# decompress
tar -C .. -xf $SRC/../linux-$VER.tar.*

# apply aufs patches
patch -p1 < $SRC/aufs3-kbuild.patch
patch -p1 < $SRC/aufs3-base.patch
patch -p1 < $SRC/aufs3-proc_map.patch
patch -p1 < $SRC/aufs3-standalone.patch
echo "header-y += aufs_type.h" >> ./include/uapi/linux/Kbuild
cp -va $SRC/Documentation .
cp -va $SRC/fs .
cp -va $SRC/include/uapi/linux/aufs_type.h ./include/uapi/linux
cp -va $SRC/include/linux/aufs_type.h ./include/linux

# make mount.aufs dynamic
cat $SRC/../aufs-util.git/Makefile | sed -r 's/ -static / /' > aaa
mv aaa $SRC/../aufs-util.git/Makefile

# configure
cat $SRC/../.config-$MYARCH >.config

# rebrand
cp $SRC/../logo_linux_clut224.ppm drivers/video/logo/

# make
make -j 8
make headers_install
cp $DST/usr/include/linux/aufs_type.h /usr/include/linux

# create package data
mkdir -p $PKG/boot
cp $DST/arch/x86/boot/bzImage $PKG/boot/vmlinuz
make modules_install INSTALL_MOD_PATH=$PKG
make firmware_install INSTALL_MOD_PATH=$PKG
mkdir -p $PKG/usr/include/linux

# create kernel headers package
KHP=/tmp/kernel-headers-package
rm -Rf $KHP
mkdir -p $KHP/usr
cp -a $DST/usr/include $KHP/usr
find $KHP | fgrep "/." | xargs rm
ln -s asm $KHP/usr/include/asm-x86
cd $KHP
/sbin/makepkg -l y -c n /tmp/kernel-headers-$VER-$MYARCH-$BUILD.txz

# compile and install aufs utils
cd $SRC/../aufs-util.git
make
make install DESTDIR=$PKG
make clean

# compile and install squashfs
cd $SRC/../squashfs4.2/squashfs-tools
sed -i -r 's/#XZ_SUPPORT = 1/XZ_SUPPORT = 1/' Makefile
make
strip --strip-unneeded mksquashfs unsquashfs
cp mksquashfs $PKG/sbin
cp unsquashfs $PKG/sbin
make install
make clean

# make final package
cd $PKG
find | xargs -I '{}' strip --strip-unneeded '{}' || true
/sbin/makepkg -l y -c n /tmp/linux-kernel-$VER-$MYARCH-$BUILD.txz
