validate_source_dir $SOURCE_DIRECTORY &&
KEEP_SOURCE=off mk_source_dir $SOURCE_DIRECTORY &&
# This fails on the CI, so don't chain it
rm -f /usr/src/linux
ln -sf $SOURCE_DIRECTORY /usr/src/linux
cd $SOURCE_DIRECTORY &&

tar xf $SOURCE_CACHE/$SOURCE --no-same-owner --no-same-permissions --strip-components=1 &&

# if we have an EXTRA patch, apply it
if [ -n "${SOURCE2}" ]; then
  patch_it ${SOURCE2} 1
fi &&

# Fix issue with patch failing to set the correct permissions
if [ -f "tools/objtool/sync-check.sh" ]; then
  chmod u+x tools/objtool/sync-check.sh
fi &&

if [ -f $CONFIG_CACHE/.config-lts ]; then
  cp $CONFIG_CACHE/.config-lts $SOURCE_DIRECTORY/.config;
elif [ -f $CONFIG_CACHE/.config.current ]; then
  cp $CONFIG_CACHE/.config.current $SOURCE_DIRECTORY/.config;
elif [ -f $CONFIG_CACHE/.config.stable ]; then
  cp $CONFIG_CACHE/.config.stable $SOURCE_DIRECTORY/.config;
fi &&

while
  if [ "$CONFIG_KERNEL" == "y" ]; then
    if [ "$PREFER_XCONFIG" == "y" -a -n "$DISPLAY" ]; then
      make xconfig || make nconfig || make menuconfig || make config
    elif [ "$PREFER_NCONFIG" == "y" ]; then
      make nconfig || make menuconfig || make config
    elif [ "$PREFER_MENUCONFIG" == "y" ]; then
      make menuconfig || make config
    else
      make config
    fi &&
    if ! query "Repeat configuration?" n; then
      CONFIG_KERNEL=n
    fi
  else
      false
  fi
do
  true
done &&

# ALWAYS append -lts as local version
if egrep -q '^CONFIG_LOCALVERSION=' $SOURCE_DIRECTORY/.config; then
   sed -i -r 's;^(CONFIG_LOCALVERSION=).*;\1"-lts";' $SOURCE_DIRECTORY/.config
else
  echo 'CONFIG_LOCALVERSION="-lts"' >> $SOURCE_DIRECTORY/.config
fi
