#!/bin/bash

#############################################################################
# Copyright (c) 2011 Novell, Inc.
# Copyright (c) 2012-2022 SUSE LLC
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.   See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact https://www.suse.com/source-code/
#
#############################################################################


# If make fails, check if it happened due to a staging driver and disable it.
# That way, staging does not spoil automatic package building and we also
# do not need to worry about forgetting to reenable manually disabled drivers.

if test -L source; then
	source="source"
else
	source="."
fi
if test -f ${source}/scripts/kconfig/Makefile && \
   grep -q syncconfig ${source}/scripts/kconfig/Makefile; then
    syncconfig="syncconfig"
else
    syncconfig="silentoldconfig"
fi
makefile="$source/drivers/staging/Makefile"
skipped_options=staging-skipped-options
logfile=$1

if test -z "$logfile"; then
	echo "Usage: $0 logfile" >&2
	exit 1
fi
if ! test -f "$logfile"; then
	echo "$logfile not found" >&2
	exit 1
fi

# safety precaution
if test "0$(wc -l "$skipped_options" 2>/dev/null)" -gt 20; then
	echo "Possible loop detected in $0, exiting after 20 attempts" >&2
	exit 1
fi

# find out if the error happened in drivers/staging
dir=$(sed -rn 's@.*/drivers/staging/([^/]*)/.*: error: .*@\1@p; T; q' "$logfile")
if test -z "$dir"; then
	exit 1
else
	echo "Build failed due to drivers/staging/$dir"
fi

option=$(sed -n 's/obj-\$(\(.*\))[[:space:]]*+=[[:space:]]*'"$dir"'\//\1/p' "$makefile")
if test -z "$option"; then
	echo "Cannot determine config option to skip drivers/staging/$dir" >&2
	exit 1
fi
# we need to be carefull not to loop endlessly
if grep -qsFx "$option" "$skipped_options"; then
	echo "$option has already been disabled, but drivers/staging/$dir is still failing" >&2
	exit 1
fi

echo "Trying to disable $option"
"$source/scripts/config" --disable "$option"
if ! make $syncconfig $MAKE_ARGS || grep "^$option" .config; then
	echo "Could not disable $option" >&2
	exit 1
fi
echo "$option" >>"$skipped_options"

exit 0
