#!/bin/bash

# Prepare updated Kernel config files & recompress the Kernel source
# for maximum compression:

CWD=$PWD

ARMBUILDSCRIPT=$CWD/../arm/build

#xz -vd linux-*tar.xz || exit 1

# Obtain existing kernel version from the arm/build script:
eval $( grep '^export VERSION=.*' $ARMBUILDSCRIPT | sed -e 's?export VERSION=? armbuildVER=?' ) || { echo "Failed to find VERSION in arm/build.. running this script from the wrong dir?" ; exit 1;}
armbuildVER="${armbuildVER/-/_}" # handle version numbers with hyphens that are switched with underscores within the SlackBuild
echo "Existing kernel version (set in 'arm/build' script): $armbuildVER"
echo "Unpacking Kernel source..."

rm -rf srcunpack
mkdir srcunpack
pushd srcunpack
  # Back these up incase:
  cp -fa $CWD/../configs .
  tar xf $CWD/linux-*.tar.?z
  cd linux-* || exit 1
  # The Kernel archive version doesn't necessarily match the version
  # exported by the Kernel itself:
  NEWKERNVER="$( sed -ne's/^VERSION *= *//p' Makefile).$(sed -ne's/^PATCHLEVEL *= *//p' Makefile).$(sed -ne's/^SUBLEVEL *= *//p' Makefile )"
  echo "New Kernel version: $NEWKERNVER"
  read -p "Press ENTER"
  ../../patches/applier

  for i in $CWD/../configs/config* ; do
    echo "***** $i *****"
    cp -fav $i .config
    make ARCH=arm oldconfig || exit 1
    cp -fav .config $i
  done || exit 1
popd

echo "Updating arm/build script with new Kernel version"
sed -i '/^export VERSION/ s?'"$armbuildVER"'?'"$NEWKERNVER"'?g' $ARMBUILDSCRIPT

# Repack with LZMA and extreme compression (kernel.org doesn't use
# extreme compression):
cd $CWD
#echo "Repacking Linux source - will take some time.."
#xz -vvez9 linux*.tar

if [ "$1" = "n" ]; then
   echo "You can now wipe srcunpack .."
 else
   rm -rf srcunpack
fi
