#!/bin/bash

ARCH=""
DIR=""
HELP=0
declare -a make=(make)

while getopts "a:cD:h" OPT; do
	case "$OPT" in
		a)
			ARCH="${OPTARG%_*}"
			DIR="$OPTARG"
			;;
		c)
			make+=('C=1')
			;;
		D)
			DESTDIR="$OPTARG"
			;;
		h)
			HELP=1
			;;
		*) exit 1
			;;
	esac
done

if [ -z "$DIR" -o \( -z "$DESTDIR" -a "$HELP" -eq 0 \) ]; then
	echo "Either -a ($DIR), or -D ($DESTDIR), or -h missing" >&2
	exit 1
fi

shift $(($OPTIND-1))

declare -A DEFCONFIGS=(
	[arm_footbridge]='footbridge_defconfig'
	[arm_pxa]='pxa_defconfig'
	[arm_rpc]='rpc_defconfig'
	[arm_sa1100]='assabet_defconfig'
	[m68k_coldfire]='m5475evb_defconfig'
	[mips_decstation]='decstation_defconfig'
	[mips_e55]='e55_defconfig'
	[mips_rbtx49xx]='rbtx49xx_defconfig'
	[mips_sb1250]='sb1250_swarm_defconfig'
	[powerpc_mpc5200]='mpc5200_defconfig'
	[powerpc_tqm8560]='85xx/tqm8560_defconfig'
)

declare -A CROSS_COMPILE=(
	[alpha]="alpha-linux-"
	[arm]="arm-suse-linux-gnueabi-"
	[arm64]="aarch64-suse-linux-"
	[loongarch]="loongarch64-linux-"
	[m68k]="m68k-linux-"
	[mips]="mips-linux-"
	[parisc]="hppa-suse-linux-"
	[powerpc]="powerpc64-suse-linux-"
	[riscv]="riscv64-suse-linux-"
	[sh]="/opt/cross/gcc-13.1.0-nolibc/sh4-linux/bin/sh4-linux-"
	[sparc]="sparc64-linux-"
	[s390]="s390x-suse-linux-"
	[xtensa]="xtensa-linux-"
)

JOBS=$(($(grep -c ^processor /proc/cpuinfo)+1))
test "$HELP" -eq 0 && make+=(O="$DESTDIR/$DIR/")
make+=("-j$JOBS" ARCH="$ARCH")

if [ "$ARCH" != "um" ]; then
	if [ -z "${CROSS_COMPILE[$ARCH]}" ]; then
		exit 1
	fi

	if ! which ${CROSS_COMPILE[$ARCH]}gcc >/dev/null && [ ! -f "${CROSS_COMPILE[$ARCH]}gcc" ]; then
		exit 1
	fi
	make+=("CROSS_COMPILE=${CROSS_COMPILE[$ARCH]}")
fi

if [ "$HELP" -eq 1 ]; then
	set -xx
	exec "${make[@]}" help
fi

if [ ! -f "$DESTDIR/$DIR/.config" ]; then
	if [ -z "${DEFCONFIGS[$DIR]}" ]; then
		echo "no config in $DESTDIR/$DIR/.config"
		exit 200
	fi
	set -xx
	"${make[@]}" "${DEFCONFIGS[$DIR]}" || exit 1
fi

set -xx

"${make[@]}" olddefconfig
exec "${make[@]}" "$@"
