#!/usr/bin/env bash
# Only clone the repo if it doesn't already exist in $pwd
if [ ! -d "linux-3.14.7" ]; then
    wget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.14.7.tar.xz -O linux-3.14.7.tar.xz
    tar xvfJ linux-3.14.7.tar.xz
    cd linux-3.14.7
    # apply ACME Systems patches
    wget http://www.acmesystems.it/www/compile_linux_3_14/acme.patch -O acme.patch
    patch -p1 < acme.patch
    # fetch kernel config
    wget http://watchmysys.com/blog/wp-content/uploads/2014/08/linux-at91.config -O .config
    # fetch patch for 256MB model
    wget http://watchmysys.com/blog/wp-content/uploads/2014/08/arietta_256m_ikconfig.patch -O arietta_256m_ikconfig.patch
    # apply patch for 256MB model
    patch -p1 < arietta_256m_ikconfig.patch
else
    cd linux-3.14.7
fi
# make clean just in case this isn't a clean tree
make ARCH=arm clean
# determine number of processors in the system
CPUS=$(cat /proc/cpuinfo | grep -c "processor")
# fetch dtb file with ADC enabled (also has ttyS1/2/3, i2c-0/1, SPI, A/D, and audio I2S enabled) 
wget http://watchmysys.com/blog/wp-content/uploads/2014/08/acme-arietta-adc.dtb -O arch/arm/boot/dts/acme-arietta.dtb
# make the kernel
make -j$CPUS ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- zImage
# make modules
make modules -j$CPUS ARCH=arm CROSS_COMPILE=arm-linux-gnueabi-
# install modules to ./modules directory
make modules_install INSTALL_MOD_PATH=./modules ARCH=arm
# create directory structure
mkdir -p modules/boot
# copy kernel
cp arch/arm/boot/zImage modules/boot/
# create archive
tar -C modules -cjvf linux-3.14.7-arietta.tar.bz2 lib/ boot/
