#! /bin/bash
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021, ARM Limited and contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -eu

export KERNEL_SRC=$(readlink -fe "$1")
export MODULE_SRC=$(readlink -fe "$2")
INSTALL_MOD_PATH=${3:-$(dirname "${BASH_SOURCE[0]}")}

export INSTALL_MOD_PATH=$(readlink -fe "$INSTALL_MOD_PATH")
export ARCH=${ARCH:-$LISA_HOST_ABI}

convert_arch() {
    case $1 in
        x86_64) echo x86;;
        aarch64) echo arm64;;
        *) echo "$1";;
    esac
}

export ARCH=$(convert_arch "$ARCH")
LISA_HOST_ABI=$(convert_arch "$LISA_HOST_ABI")

echo "Building module for ARCH=$ARCH"

case $ARCH in
	$LISA_HOST_ABI)
		;;
	arm64)
		export CROSS_COMPILE=${CROSS_COMPILE:-aarch64-linux-gnu-}
		;;
	arm)
		export CROSS_COMPILE=${CROSS_COMPILE:-arm-linux-gnueabi-}
		;;
	*)
		echo "ERROR: Unknown ARCH=$ARCH" >&2
		exit 1
		;;
esac

make -C "$MODULE_SRC"
