#!/bin/bash

prefix=/usr/local
kerneldir=/lib/modules/$(uname -r)/build
cc=gcc
ld=ld
objcopy=objcopy
ar=ar
arch=`uname -m | sed -e s/i.86/i386/ | sed -e 's/arm.*/arm/'`
cross_prefix=

usage() {
    cat <<-EOF
	Usage: $0 [options]

	Options include:
	    --arch=ARCH            architecture to compile for ($arch)
	    --processor=PROCESSOR  processor to compile for ($arch)
	    --cross-prefix=PREFIX  cross compiler prefix
	    --cc=CC		   c compiler to use ($cc)
	    --ld=LD		   ld linker to use ($ld)
	    --prefix=PREFIX        where to install things ($prefix)
	    --kerneldir=DIR        kernel build directory for kvm.h ($kerneldir)
EOF
    exit 1
}

while [[ "$1" = -* ]]; do
    opt="$1"; shift
    arg=
    if [[ "$opt" = *=* ]]; then
	arg="${opt#*=}"
	opt="${opt%%=*}"
    fi
    case "$opt" in
	--prefix)
	    prefix="$arg"
	    ;;
	--kerneldir)
	    kerneldir="$arg"
	    ;;
        --arch)
	    arch="$arg"
	    ;;
        --processor)
	    processor="$arg"
	    ;;
	--cross-prefix)
	    cross_prefix="$arg"
	    ;;
	--cc)
	    cc="$arg"
	    ;;
	--ld)
	    ld="$arg"
	    ;;
	--help)
	    usage
	    ;;
	*)
	    usage
	    ;;
    esac
done

arch_name=$arch
[ "$arch" = "aarch64" ] && arch="arm64"
[ "$arch_name" = "arm64" ] && arch_name="aarch64"

[ -z "$processor" ] && processor="$arch"

if [ "$processor" = "arm64" ]; then
    processor="cortex-a57"
elif [ "$processor" = "arm" ]; then
    processor="cortex-a15"
fi

if [ "$arch" = "i386" ] || [ "$arch" = "x86_64" ]; then
    testdir=x86
elif [ "$arch" = "arm" ] || [ "$arch" = "arm64" ]; then
    testdir=arm
else
    testdir=$arch
fi
if [ ! -d $testdir ]; then
    echo "$testdir does not exist!"
    exit 1
fi
if [ -f $testdir/run ]; then
    ln -fs $testdir/run $testdir-run
fi

# check for dependent 32 bit libraries
if [ "$arch" != "arm" ]; then
cat << EOF > lib_test.c
#include <stdc++.h>
#include <boost_thread-mt.h>
#include <pthread.h>

int main ()
{}
EOF
$cc -m32 -o /dev/null lib_test.c &> /dev/null
exit=$?
if [ $exit -eq 0 ]; then
    api=true
fi
rm -f lib_test.c
fi

# link lib/asm for the architecture
rm -f lib/asm
asm=asm-generic
if [ -d lib/$arch/asm ]; then
	asm=$arch/asm
elif [ -d lib/$testdir/asm ]; then
	asm=$testdir/asm
fi
ln -s $asm lib/asm

# create the config
cat <<EOF > config.mak
PREFIX=$prefix
KERNELDIR=$(readlink -f $kerneldir)
ARCH=$arch
ARCH_NAME=$arch_name
PROCESSOR=$processor
CC=$cross_prefix$cc
LD=$cross_prefix$ld
OBJCOPY=$cross_prefix$objcopy
AR=$cross_prefix$ar
API=$api
TEST_DIR=$testdir
EOF
