#!/bin/bash
###############################################################################
# IPFire.org    - An Open Source Firewall Solution                            #
# Copyright (C) - IPFire Development Team <info@ipfire.org>                   #
###############################################################################

BASEDIR="$(dirname "${0}")"
SCRIPTS_DIR="${BASEDIR}"

# The directory that holds the configuration files
CONFIG_DIR="/usr/src/config/kernel"

CONFIGS=(
	# x86_64
	"x86_64:generic"

	# aarch64
	"aarch64:generic"

	# riscv64
	"riscv64:generic"

	# loongarch64
	"loongarch64:generic"
)

search_kernel_dir() {
	local dir
	for dir in /builddir/source/linux-*; do
		if [ -d "${dir}" ]; then
			echo "${dir}"
			break
		fi
	done
}

arches() {
	local config
	for config in ${CONFIGS[@]}; do
		echo "${config%:*}"
	done
}

flavours_for_arch() {
	local arch="${1}"

	local config
	for config in ${CONFIGS[@]}; do
		if [ "${arch}:" = "${config%:*}:" ]; then
			echo "${config#*:}"
		fi
	done
}

configs() {
	local arch="${1}"
	local flavour="${2}"
	shift 2

	# Add any extra files first
	local configs=( "$@" )

	# Add the generic configuration
	configs+=( "${CONFIG_DIR}/config-generic" )

	# If flavour is not generic, we add *-generic
	if [ "${flavour}" != "generic" ]; then
		configs+=( "${CONFIG_DIR}/config-${arch}-generic" )
	fi

	# Add the architecture/flavour configuration
	configs+=( "${CONFIG_DIR}/config-${arch}-${flavour}" )

	# Return the result
	echo "${configs[@]}"

	return 0
}

get_kernel_arch() {
	local arch="${1}"

	case "${arch}" in
		aarch64)
			echo "arm64"
			;;
		loongarch64)
			echo "loongarch"
			;;
		riscv64)
			echo "riscv"
			;;
		x86_64)
			echo "x86"
			;;
		*)
			echo "${arch}"
			;;
	esac
}

kernel_config() {
	local arch="${1}"
	local action="${2}"
	local config_in="${3}"
	local config_out="${4}"

	echo "Running 'make ${action}' for ${arch}..."

	local kernel_arch="$(get_kernel_arch "${arch}")"

	pushd "${KERNEL_DIR}" >/dev/null

	cat "${config_in}" > ".config"

	# Run the configuration program
	make ARCH="${kernel_arch}" "${action}"

	# Write back the configuration file
	cat ".config" > "${config_out}"

	popd >/dev/null
}

merge_config() {
	local arch="${1}"
	local flavour="${2}"
	local output="${3}"
	shift 3

	local arg
	for arg in arch flavour output; do
		if [ -z "${!arg}" ]; then
			echo >&2 "merge usage: <arch> <flavour> <output filename>"
			return 2
		fi
	done

	local configs="$(configs "${arch}" "${flavour}" "$@")"

	# Merge the configuration files from its elementary configuration
	# files.
	local tmp_out="$(mktemp)"
	local tmp_in="$(mktemp)"

	local config
	for config in ${configs}; do
		cat "${tmp_out}" > "${tmp_in}"

		if ! perl "${SCRIPTS_DIR}/merge.pl" \
				"${tmp_in}" "${config}" > "${tmp_out}"; then
			echo >&2 "Could not merge configuration for ${arch} ${flavour}"
			rm -f "${tmp_in}" "${tmp_out}"
			return 1
		fi
	done

	cat "${tmp_out}" > "${output}"
	rm -f "${tmp_in}" "${tmp_out}"
}

# This function runs an interactive "make oldconfig"
make_config() {
	local action="${1}"
	local arch="${2}"

	# Default to the architecture of this host when no arch is given
	if [ -z "${arch}" ]; then
		arch="$(uname -m)"
	fi

	# Detect kernel arch
	local flavour="generic"

	# Create a temporary directory
	local tmpdir="$(mktemp -d)"

	# Merge configuration
	if ! merge_config "${arch}" "${flavour}" "${tmpdir}/.config.old"; then
		echo "Could not merge configuration for ${arch} (${flavour})" >&2
		return 1
	fi

	# Open the kernel configuration editor (in the given mode)
	if ! kernel_config "${arch}" "${action}" "${tmpdir}/.config.old" "${tmpdir}/.config"; then
		echo >&2 "Kernel configuration editing has been unsuccessful"
		rm -rf "${tmpdir}"
		return 1
	fi

	# Diff the old and changed configuration
	if ! python3 "${SCRIPTS_DIR}/configdiff.py" \
			"${tmpdir}/.config.old" "${tmpdir}/.config" > "${tmpdir}/diff"; then
		rm -rf "${tmpdir}"
		return 1
	fi

	# Apply the diff to all configurations
	if ! diff_configs "${tmpdir}/diff"; then
		rm -rf "${tmpdir}"
		return 1
	fi

	# Cleanup
	rm -rf "${tmpdir}"

	return 0
}

diff_configs() {
	local tmpdir="$(mktemp -d)"

	local configs=()

	local config
	for config in ${CONFIGS[@]}; do
		arch="${config%:*}"
		flavour="${config#*:}"

		# Generate the filename
		local filename="${tmpdir}/full-${arch}-${flavour}"

		# Merge configuration
		if ! merge_config "${arch}" "${flavour}" "${filename}" "$@"; then
			rm -rf "${tmpdir}"
			return 1
		fi

		# Fetch the configuration as it is currently stored
		if ! merge_config "${arch}" "${flavour}" "${filename}.stored"; then
			rm -rf "${tmpdir}"
			return 1
		fi

		# Run "oldconfig" to ensure there are no gaps in other architectures
		kernel_config "${arch}" "oldconfig" "${filename}" "${filename}.new"

		# Collect all *-generic configurations
		case "${flavour}" in
			generic)
				configs+=( "${filename}" )
				;;
		esac
	done

	# The compiler of this host cannot tell which features are supported on
	# any other architecture and so Kconfig drops all options that depend on
	# them. Put back what we have had before, unless it has been dropped for
	# the architecture of this host, too.
	local native="${tmpdir}/full-$(uname -m)-generic"

	for config in ${CONFIGS[@]}; do
		local filename="${tmpdir}/full-${config%:*}-${config#*:}"

		if [ "${config%:*}" = "$(uname -m)" ]; then
			cat "${filename}.new" > "${filename}"
			continue
		fi

		local args=( "${filename}.stored" "${filename}" "${filename}.new" )
		if [ -e "${native}.new" ]; then
			args+=( "${native}.stored" "${native}.new" )
		fi

		if ! python3 "${SCRIPTS_DIR}/configrestore.py" "${args[@]}" \
				> "${filename}.restored"; then
			echo >&2 "Could not restore configuration for ${config}"
			rm -rf "${tmpdir}"
			return 1
		fi

		cat "${filename}.restored" > "${filename}"
	done

	# Generate config-generic
	if ! python3 "${SCRIPTS_DIR}/configcommon.py" "${configs[@]}" \
			> "${tmpdir}/config-generic"; then
		echo >&2 "Could not generate config-generic"
		rm -rf "${tmpdir}"
		return 1
	fi

	local arch
	for arch in $(arches); do
		# Fetch all flavours
		local flavours="$(flavours_for_arch "${arch}")"

		local flavour
		for flavour in ${flavours}; do
			local base_config="${tmpdir}/config-${arch}-generic"

			# config-${arch}-generic is handled in a special way and diffed
			# directly against config-generic
			case "${flavour}" in
				generic)
					base_config="${tmpdir}/config-generic"
					;;
			esac

			# Diff configurations
			if ! python3 "${SCRIPTS_DIR}/configdiff.py" \
					"${base_config}" \
					"${tmpdir}/full-${arch}-${flavour}" \
					> "${tmpdir}/config-${arch}-${flavour}"; then
				echo >&2 "Could not generate config-${arch}-${flavour}"
				rm -rf "${tmpdir}"
				return 1
			fi
		done
	done

	# Enter the temporary directory
	pushd "${tmpdir}" >/dev/null

	# List any changes and copy back the result
	for config in config-*; do
		if ! cmp "${tmpdir}/${config}" "${CONFIG_DIR}/${config}" &>/dev/null; then
			echo "${config} has changed"
		fi

		# Copy back configuration
		cat "${tmpdir}/${config}" > "${CONFIG_DIR}/${config}"
	done

	# Leave the temporary directory
	popd >/dev/null

	# Cleanup
	rm -rf "${tmpdir}"

	return 0
}

KERNEL_DIR="$(search_kernel_dir)"

main() {
	local action

	# Parse commandline
	local arg
	while [ $# -gt 0 ]; do
		arg="${1}"
		shift

		case "${arg}" in
			--kernel-dir=*)
				KERNEL_DIR="${arg#--kernel-dir=}"
				;;

			listnewconfig|menuconfig|merge|oldconfig|olddefconfig)
				action="${arg}"
				break
				;;

			help|"")
				echo "${0} - available commands:"
				echo "    * merge <arch> <flavour> <output filename>"
				echo "    * menuconfig"
				echo "    * oldconfig"
				echo "    * olddefconfig"
				return 0
				;;
		esac
	done

	# Check if KERNEL_DIR has been set and exists
	if [ -z "${KERNEL_DIR}" -o ! -d "${KERNEL_DIR}" ]; then
		echo >&2 "KERNEL_DIR was not set or does not exist!"
		return 2
	fi

	case "${action}" in
		merge)
			merge_config "$@"
			return $?
			;;

		listnewconfig|menuconfig|oldconfig|olddefconfig)
			make_config "${action}" "$@"
			return $?
			;;

		# Handle no or invalid actions
		*)
			echo >&2 "No action given... Try ${0} help."
			return 2
			;;
	esac
}

main "$@" || exit $?
