#!/bin/sh
# -*- mode: shell-script; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
#
# Copyright (C) 2012, 2013 O.S. Systems Software LTDA.
# Authored-by:  Otavio Salvador <otavio@ossystems.com.br>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Add options for the script
# Copyright (C) 2013 Freescale Semiconductor, Inc.
# Copyright (C) 2014 Garz & Fricke GmbH

NCPU=`grep -c processor /proc/cpuinfo`
CWD=`pwd`
PROGNAME="setup-environment"

usage()
{
    echo -e "\nUsage: source $PROGNAME <build-dir>
    <build-dir>: specifies the build directory location (required)

If undefined, this script will set \$MACHINE to 'santaro'.

Supported machines: `echo; find sources -path "*meta*/machine/*.conf" \
| sed s/\.conf//g | sed -r 's/^.+\///' | xargs -I% echo -e "\t%"`

To build for a machine listed above, run this script as:
MACHINE=<machine> source $PROGNAME <build-dir>
"
}

clean_up()
{
   unset EULA LIST_MACHINES VALID_MACHINE
   unset NCPU CWD TEMPLATES SHORTOPTS LONGOPTS ARGS PROGNAME
   unset generated_config updated
   unset MACHINE SDKMACHINE DISTRO OEROOT
}

# get command line options
SHORTOPTS="h"
LONGOPTS="help"

ARGS=$(getopt --options $SHORTOPTS  \
  --longoptions $LONGOPTS --name $PROGNAME -- "$@" )
# Print the usage menu if invalid options are specified
if [ $? != 0 -o $# -lt 1 ]; then
   usage && clean_up
   return 1
fi

eval set -- "$ARGS"
while true;
do
    case $1 in
        -h|--help)
           usage
           clean_up
           return 0
           ;;
        --)
           shift
           break
           ;;
    esac
done

if [ "$(whoami)" = "root" ]; then
    echo "ERROR: do not use the BSP as root. Exiting..."
fi

if [ -z "$MACHINE" ]; then
    MACHINE='santaro-santoka'
fi

# Check the machine type specified
LIST_MACHINES=`find sources -path "*meta*/machine/*.conf"`
VALID_MACHINE=`echo -e "$LIST_MACHINES" | grep ${MACHINE}.conf$ | wc -l`
if [ "x$MACHINE" = "x" ] || [ "$VALID_MACHINE" = "0" ]; then
    echo -e "\nThe \$MACHINE you have specified ($MACHINE) is not supported by this build setup"
    usage && clean_up
    return 1
else
    if [ ! -e $1/conf/local.conf.sample ]; then
        echo "Configuring for ${MACHINE}"
    fi
fi

if [ -z "$SDKMACHINE" ]; then
    SDKMACHINE='i686'
fi

if [ -z "$DISTRO" ]; then
    DISTRO='guf'
fi

if [ -z "$DISTRO_CONFIGURATION" ]; then
    first_configuration_folder=`find sources/meta-guf/* -name "meta-*" | sort | head -1`
    DISTRO_CONFIGURATION=${first_configuration_folder##*-}
fi

OEROOT=sources/poky
if [ -e sources/oe-core ]; then
    OEROOT=sources/oe-core
fi

cd $OEROOT

. ./oe-init-build-env $CWD/$1 > /dev/null

# Clean up PATH, because if it includes tokens to current directories somehow,
# wrong binaries can be used instead of the expected ones during task execution
export PATH="`echo $PATH | sed 's/\(:.\|:\)*:/:/g;s/^.\?://;s/:.\?$//'`"

generated_config=
if [ ! -e conf/local.conf.sample ]; then
    mv conf/local.conf conf/local.conf.sample

    # Generate the local.conf based on the Yocto defaults
    TEMPLATES=$CWD/sources/base/conf 
    grep -v '^#\|^$' conf/local.conf.sample > conf/local.conf
    cat >> conf/local.conf <<EOF

BB_NUMBER_THREADS = '$NCPU'
PARALLEL_MAKE = '-j $NCPU'

DL_DIR ?= "\${BSPDIR}/downloads/"

INHERIT += "buildhistory"
BUILDHISTORY_COMMIT = "0"
BUILDHISTORY_FEATURES = "image"

SSTATE_DIR = "$(dirname $PWD)/sstate-cache"
PRSERV_HOST = "localhost:0"

EOF
    # Change settings according environment
    sed -e "s,MACHINE ??=.*,MACHINE ??= '$MACHINE',g" \
        -e "s,SDKMACHINE ??=.*,SDKMACHINE ??= '$SDKMACHINE',g" \
        -e "s,DISTRO ?=.*,DISTRO ?= '$DISTRO',g" \
        -i conf/local.conf

    cp $TEMPLATES/* conf/

    for s in $HOME/.oe $HOME/.yocto; do
        if [ -e $s/site.conf ]; then
            echo "Linking $s/site.conf to conf/site.conf"
            ln -s $s/site.conf conf
        fi
    done

	# Add meta-guf/meta-$DISTRO_CONFIGURATION before! the existing layers
	# ( the priority of the conf files is set by the sequence here and not by the priority flag, grr.
	sed -i "/BBLAYERS = \"/i DISTRO_CONFIGURATION = \"${DISTRO_CONFIGURATION}\"\
		" conf/bblayers.conf
	sed -i '/BBLAYERS = " \\/a \
  \${BSPDIR}/sources/meta-guf/meta-\${DISTRO_CONFIGURATION} \\' conf/bblayers.conf

    generated_config=1
fi

# Handle EULA setting
if [ -z "$EULA" ] && ! grep -q '^ACCEPT_FSL_EULA\s*=' conf/local.conf; then
    EULA='ask'
fi

if [ "$EULA" = "ask" ]; then
    cat <<EOF

Some BSPs depend on libraries and packages which are covered by Freescale's
End User License Agreement (EULA). To have the right to use these binaries in
your images, you need to read and accept the following...

EOF

    sleep 4

    more -d $CWD/sources/meta-fsl-arm/EULA
    echo
    while [ "$EULA" = "ask" ]; do
        echo -n "Do you accept the EULA you just read? (y/n) "
        read REPLY
        case "$REPLY" in
            y|Y)
            echo "EULA has been accepted."
            EULA="1"
            ;;
            n|N)
            echo "EULA has not been accepted."
            EULA="0"
            ;;
        esac
    done
fi

export BB_ENV_EXTRAWHITE="$BB_ENV_EXTRAWHITE CHROMIUM_VERSION"

if grep -q '^ACCEPT_FSL_EULA\s*=' conf/local.conf; then
    sed -i "s/^#*ACCEPT_FSL_EULA\s*=.*/ACCEPT_FSL_EULA = \"$EULA\"/g" conf/local.conf
else
    echo "ACCEPT_FSL_EULA = \"$EULA\"" >> conf/local.conf
fi

cat <<EOF

Welcome to Garz & Fricke Yocto BSP
based on Freescale Community BSP

The Yocto Project has extensive documentation about OE including a
reference manual which can be found at:
    http://yoctoproject.org/documentation

For more information about OpenEmbedded see their website:
    http://www.openembedded.org/

You can now run 'bitbake <target>'

Common targets are:
    core-image-minimal
    meta-toolchain
    meta-toolchain-sdk
    adt-installer
    meta-ide-support
    guf-image

EOF

if [ -n "$generated_config" ]; then
    cat <<EOF
Your build environment has been configured with:

    MACHINE=$MACHINE
    SDKMACHINE=$SDKMACHINE
    DISTRO=$DISTRO
    DISTRO_CONFIGURATION=$DISTRO_CONFIGURATION
    EULA=$EULA
EOF
else
    echo "Your configuration files at $1 have not been touched."
fi

clean_up
