#!/bin/bash
set -vx
# This script is used by KCS server to build and upload kernels.
# If repository REPO_ID exists, it pulls and checkouts to COMMIT.
# Environment variables can be set:
# REPO_DIR GS_BUCKET GS_PATH GS_CONFIG KCONFIG_OPTS KBUILD_ARCH

function install_kconfig () {
    if test -z "$KCONFIG_OPTS" ; then
	(cd "$REPO_DIR" ; gce-xfstests install-kconfig \
		--arch "$KBUILD_ARCH") || exit 1
    else
	local array=($(echo $KCONFIG_OPTS | sed -e 's/,/ /g'))

	(cd "$REPO_DIR" ; gce-xfstests install-kconfig \
		--arch "$KBUILD_ARCH" "${array[@]}") || exit 1
    fi
}

if test -z "$KBUILD_ARCH" ; then
    KBUILD_ARCH=$(dpkg --print-architecture)
fi
KBUILD_OPTS="$KBUILD_OPTS --arch $KBUILD_ARCH"
image=bzImage
archdir=x86_64
if test "$ARCH" = "arm64" ; then
	image=Image
	archdir=arm64
fi

if command -v ccache &> /dev/null /cache/ccache ; then
    export PATH="/usr/lib/ccache:$PATH"
    export CCACHE_DIR=/cache/ccache
fi

if test -z "$REPO_DIR"; then
    REPO_DIR="."
fi

echo -n "Building in "
(cd $REPO_DIR ; pwd ; git log --oneline -1)

if test -z "$GS_PATH"; then
    GS_PATH="gs://$GS_BUCKET/bzImage"
fi

if test -n "$GS_CONFIG" ; then
    if gsutil cp "$GS_CONFIG" "$REPO_DIR/.config" ; then
	if test $(stat -c %s "$REPO_DIR/.config") -gt 16384 ; then
	    (cd "$REPO_DIR" ; make oldconfig) || exit 1
	else
	    (cd "$REPO_DIR" ; make olddefconfig) || exit 1
	fi
    else
	install_kconfig
    fi
else
    install_kconfig
fi
KERNEL_PATH="$REPO_DIR/arch/$archdir/boot/$image"
DPKG_FLAGS=
if [[ $GS_PATH == *.deb ]]; then
    DPKG_FLAGS=--dpkg
    KERNEL_PATH="$REPO_DIR/linux-image.deb"
fi

cc=gcc
if grep -q CONFIG_CC_IS_CLANG=y "$REOP_DIR/.config" 2>/dev/null ; then
    cc=clang
fi
$cc --version > "$REPO_DIR/.cc-version-new"
if cmp -s "$REPO_DIR/.cc-version" "$REPO_DIR/.cc-version-new"
then
    rm -f "$REPO_DIR/.cc-version-new"
else
    (cd "$REPO_DIR" ; gce-xfstests kbuild clean)
    mv "$REPO_DIR/.cc-version-new" "$REPO_DIR/.cc-version"
fi

status=1
trap "rm -f /run/kernel-building; exit \$status" EXIT HUP INT QUIT TERM
touch "$REPO_DIR/last-used" "$REPO_DIR/last-touched" /run/kernel-building
test -f "$REPO_DIR/modules.order" || touch "$REPO_DIR/modules.order"
(cd "$REPO_DIR" ; time gce-xfstests kbuild $DPKG_FLAGS $KBUILD_OPTS) || exit 1
status=0
rm -f /run/kernel-building
gce-xfstests upload-kernel --kernel "$KERNEL_PATH" $GS_PATH
