# --- SDE-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
#
# Filename: package/.../linux/linux-conf.in
# Copyright (C) 2006 - 2012 The OpenSDE Project
# Copyright (C) 2004 - 2006 The T2 SDE Project
# Copyright (C) 1998 - 2003 Clifford Wolf
#
# More information can be found in the files COPYING and README.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- SDE-COPYRIGHT-NOTE-END ---

treever=$(echo $ver | cut -d. -f1-2 | tr -d .)

lx_confdir=$(pkgdesc confdir linux)
lx_ver=0
for x in $(echo "$ver" | cut -d- -f1 | cut -d. -f1-3 | tr '.' ' '); do
	lx_ver=$( expr $lx_ver \* 1000 + $x )
done

if [ $lx_ver -lt 1000000 ]; then
	lx_ver=${lx_ver}000
fi

lx_cpu="$arch_machine"
if [ -s "$lx_confdir/arch/$arch.in" ]; then
	. "$lx_confdir/arch/$arch.in"
else
	. "$lx_confdir/arch/shared.in"
fi

lx_extraversion=
lx_kernelrelease=

lx_customconf="${SDECFG_PKG_LINUX_CONFIG_FILE:-config/$config/linux.cfg}"

# $lx_confmerge list of config snaps gets merged to .config.3 on auto_config()
#
lx_confmerge=
for x in $base/config/$config/linux.cfg \
	$( get_expanded $base/target/%/kernel${treever}.conf `get_reverted $targetchain` ) \
	$( get_expanded $base/target/%/kernel.conf `get_reverted $targetchain` ); do
	if [ -f "$x" ]; then
		var_append lx_confmerge ' ' "$x"
	fi
done

# $lx_confscripts list of scripts to alter .config.2 generating .config.3 on auto_config()
lx_confscripts=
for x in $base/target/$target/kernel$treever.conf.sh \
	 $base/target/$target/kernel.conf.sh ; do
	if [ -f "$x" ]; then
		var_append lx_confscripts ' ' "$x"
		break
	fi
done

# inject a possible pre-/ post-release patch
# we filter out .tar`s to avoid trouble with the linuxsh kernel drop-in trees
var_insert patchfiles " " "`match_source_file patch-.* | grep -v '\.tar\.'`"

#makeopt=`echo $makeopt | sed -n 's/.*\(-j[^ ]*\).*/\1/p'`
makeopt=
# we need +1 to really saturate the CPUs during the kernel build
[ $SDECFG_PARALLEL_MAX -gt 1 ] &&
	var_append makeopt ' ' -j$(( $SDECFG_PARALLEL_MAX + 1 ))

var_append makeopt ' ' "ARCH=$lx_cpu CROSS_COMPILE=$archprefix KCC=$KCC LOCALVERSION="
makeinstopt="$makeopt"

auto_config_merge() {
	local rules="$1" tag=
	echo "  merging: '$rules'" >&2
	tag="$(sed '/CONFIG_/ ! d; s,.*CONFIG_\([^ =]*\).*,\1,' \
		"$rules" | tr '\n' '|')"
	egrep -v "\bCONFIG_($tag)\b" < .config
	sed 's,\(CONFIG_.*\)=n,# \1 is not set,' "$rules"
}

auto_config() {
	local x= loop=
	# get defconfig (.config.0)
	#
	echo "Creating linux default config"
	case "$SDECFG_PKG_LINUX_CONFIG_STYLE" in
		none)
			abort "auto_config: shouldn't reach this point."
			;;
		defconfig|humble|nomodules)
			eval $MAKE $makeopt defconfig
			;;
		allmodules)
			eval $MAKE $makeopt allmodconfig
			;;
	esac
	cp .config{,.0}
	# architecture specific configuration (will be merged)
	if [ -f "$lx_confdir/arch/config.$arch.sh" ]; then
		sh "$lx_confdir/arch/config.$arch.sh" "$lx_ver" > .config.$arch
	else
		echo_warning "No config scripts found for this architecture ($arch)."
		echo > .config.$arch
	fi

	# inject CONFIG_INITRAMFS_SOURCE if set
	if [ -n "$SDECFG_PKG_LINUX_EARLY_FILE" ]; then
		x="$SDECFG_PKG_LINUX_EARLY_FILE"
		expr "$x" : '/*' > /dev/null || x="$base/$x"

		sed -i '/CONFIG_INITRAMFS_SOURCE/d;' .config.$arch
		echo "CONFIG_INITRAMFS_SOURCE=\"$x\"" >> .config.$arch
	fi

	if [ -s .config.$arch ]; then
		# apply $arch specific rules
		#
		for loop in 1 2; do
			auto_config_merge .config.$arch > .config.1.$loop.0
			cp .config{.1.$loop.0,}

			# create a valid .config
			#
			yes '' | eval $MAKE $makeopt oldconfig > /dev/null ; cp .config{,.1.$loop}
		done

	fi

	if [ "$SDECFG_PKG_LINUX_CONFIG_STYLE" != "humble" ]; then
		# all modules needs to be first so modules can be disabled by i.e.
		# the targets later
		echo "Enabling all modules ..."
		yes '' | eval $MAKE $makeopt no2modconfig > /dev/null ; cp .config{,.2}
	fi

	# for "safety" we will apply the config twice, so hidden options have time
	# to appear
	#
	for loop in 1 2; do
		# call scripts to tweak the config file
		#
		for x in $lx_confscripts ; do
			echo "  running: $x"
			sh $x .config
		done
		cp .config{,.3.$loop}

		# merge various text/plain config files
		#
		for x in $lx_confmerge; do
			if [ -f $x ] ; then
				auto_config_merge "$x" > .config.4.$loop
				cp .config{.4.$loop,}
			else
				echo_warning "Can't find '${x#$base/}' for merging."
			fi
		done

		# create a valid .config
		#
		yes '' | eval $MAKE $makeopt oldconfig > /dev/null ; cp .config{,.5.$loop}
	done

	# last disable broken stuff
	#
	rm -f /tmp/$$.sed
	list="CONFIG_THIS_DOES_NOT_EXIST"
	for x in $pkg_linux_brokenfiles ; do
		if [ -f "$x" ] ; then
			echo "Disable broken file: $x"
			list="$list `tr ' ' '\t' < $x | cut -f1 | grep '^CONFIG_'`"
		fi
	done
	for x in $list ; do
		echo "s,^$x=.\$,# $x is not set,;" >> /tmp/$$.sed
	done
	sed -f /tmp/$$.sed < .config > .config.6
	rm -f /tmp/$$.sed
	cp .config{.6,}

	# create a valid .config (dependencies might need to be disabled)
	yes '' | eval $MAKE $makeopt oldconfig > /dev/null

	# save final config (with modules)
	cp .config{,_modules}

	echo "Creating config without modules ...."
	sed "s,\(CONFIG_.*\)=m,# \1 is not set," .config > .config_new
	mv .config_new .config
	# create a valid .config (dependencies might need to be disabled)
	yes '' | eval $MAKE $makeopt oldconfig > /dev/null
	mv .config .config_nomods

	# which .config to use?
	if [ "$SDECFG_PKG_LINUX_CONFIG_STYLE" != "nomodules" ] ; then
		cp .config{_modules,}
	else
		cp .config{_nomods,}
	fi
}

lx_grabextraversion () {
	local ev
	ev=$( sed -n -e 's,^[ \t]*EXTRAVERSION[ \t]*=[ \t]*\([^ \t]*\),\1,p' Makefile | tail -n 1 )
	if [ "$ev" ]; then
		lx_extraversion="${lx_extraversion}${ev}"
		# keep intact but commented since the second EXTRAVERSION
		# definition, and clean the first.
		sed -i -e 's,^\([ \t]*EXTRAVERSION[ \t]*=.*\),#\1,g' \
		       -e 's,^#\(EXTRAVERSION =\).*,\1,' Makefile
	fi
}
lx_injectextraversion () {
	local version_header=linux/version.h
	local rerun=

	if [ -f include/linux/utsrelease.h ]; then
		version_header=linux/utsrelease.h
	fi

	if [ -f include/generated/utsrelease.h ]; then
		version_header=generated/utsrelease.h
	fi

	# inject final EXTRAVERSION into Makefile
	sed -i -e "s,^\([ \t]*EXTRAVERSION[ \t]*\)=.*,\1= ${lx_extraversion},g" Makefile

	# update version.h - we only do this, because some other freaky
	# projects like rsbac change EXTRAVERSION in other Makefiles ...
	eval $MAKE $makeopt include/$version_header | grep -q "is up to date" && rerun=1
	if [ "$rerun" ] ; then
		echo "WARNING: Your system's timer resolution is too low ..."
		sleep 1 ; touch Makefile
		eval $MAKE $makeopt include/$version_header
	fi

	# get kernel_release
	rerun=1
	while true; do
		lx_kernelrelease="$( echo -e "#include <$version_header>\nUTS_RELEASE" |
		                     gcc -E -I./include - | tail -n 1 | cut -d '"' -f 2 )"
		if [ -z "$lx_kernelrelease" -a "$rerun" ]; then
			$MAKE $makeopt .kernelrelease include/$version_header
			rerun= ; continue
		fi
		break
	done

	[ $lx_kernelrelease ] || abort "Could not grab final kernel version!"
}

lx_filter_patch ()
{
	pref=`sed -n '/^-EXTRAVERSION =/ {
	              s/^-EXTRAVERSION =//p
	              q }' $1`
	sed -e "s/^-EXTRAVERSION =.*/-EXTRAVERSION =/" \
	    -e "s/^+EXTRAVERSION = *$pref/+EXTRAVERSION = /" $1
}

lx_patch ()
{
	# validate ARCH
	[ -d "arch/$lx_cpu/" ] || abort "architecture ($lx_cpu) not known by this kernel."

	echo "Generic linux patching ..."

	# grab extraversion from vanilla
	lx_grabextraversion

	hook_eval prepatch
	apply_patchfiles lx_grabextraversion lx_filter_patch
	hook_eval postpatch

	# some arches (sh64 at the time of writing) have a "defect" Makefile
	# and do not work without a .config ...
	touch .config

	echo "Redefining VERSION  ..."
	lx_extraversion="${lx_extraversion}-dist"
	lx_injectextraversion
	echo "... linux source patching for ${lx_extraversion} finished."

	echo "Correcting user and permissions ..."
	chown -R root:root . ; chmod -R u=rwX,go=rX .

	if [ "$lx_kernelrelease" != "UTS_RELEASE" ]; then
		echo "Create symlinks and a few headers for <$lx_cpu> ... "
		eval $MAKE $makeopt include/asm
	fi

	echo "Clean up the *.orig and *~ files ... "
	rm -f .config.old
	find -name '*.orig' -o -name '*~' | xargs rm -f
}

lx_config() {
	echo "Generic linux configuration ..."
	hook_eval preconf
	if [ "$SDECFG_PKG_LINUX_CONFIG_STYLE" = none ] ; then
		echo_status "Using only ${lx_customconf}."
		if expr "$lx_customconf" : '/*' > /dev/null; then
			cp -vf "$lx_customconf" .config
		else
			cp -vf "$base/$lx_customconf" .config
		fi
		eval $MAKE $makeopt oldconfig
	else
		echo "Automatically creating default configuration ...."
		auto_config
	fi

	if [ "$lx_kernelrelease" == "UTS_RELEASE" ]; then
		# we have to run make prepare
		eval $MAKE $makeopt prepare
	fi

	# regrab the version
	lx_injectextraversion

	[ "$lx_kernelrelease" != "UTS_RELEASE" ] ||
		abort "Unable to detect kernel release version!"
	echo "... configuration of $lx_kernelrelease finished!"
}

pkg_linux_brokenfiles="$base/architecture/$arch/kernel$treever-disable.lst \
	$base/package/*/linux$treever/disable-broken.lst \
	$pkg_linux_brokenfiles"

# if the fhs package is enabled, remove 'lib/firmware' from file list because
# then this directory belongs to the fhs package
if pkginstalled fhs; then
	var_append flistdel "|" "lib/firmware"
fi