###########################################################################
# Copyright (C) 2015-2021 IoT.bzh Company
#
# Author: Clément Bénier <clement.benier@iot.bzh>
# Author: Romain Forlot <romain.forlot@iot.bzh>
#
# $RP_BEGIN_LICENSE$
# Commercial License Usage
#  Licensees holding valid commercial IoT.bzh licenses may use this file in
#  accordance with the commercial license agreement provided with the
#  Software or, alternatively, in accordance with the terms contained in
#  a written agreement between you and The IoT.bzh Company. For licensing terms
#  and conditions see https://www.iot.bzh/terms-conditions. For further
#  information use the contact form at https://www.iot.bzh/contact.
#
# GNU General Public License Usage
#  Alternatively, this file may be used under the terms of the GNU General
#  Public license version 3. This license is as published by the Free Software
#  Foundation and appearing in the file LICENSE.GPLv3 included in the packaging
#  of this file. Please review the following information to ensure the GNU
#  General Public License requirements will be met
#  https://www.gnu.org/licenses/gpl-3.0.html.
# $RP_END_LICENSE$
###########################################################################

#!/bin/bash

log() {
	[ $VERBOSE ] && echo "$@"
}

error() {
	echo "[ERROR]: $@"
	exit 2
}

usage() {
    echo "Usage: $(basename $0) [-h|--help] [-s|--switch-arch] [-i|--info]"
    echo " -i|--info\t\tgetting info about current setup"
    echo " -s|--switch-arch\t\tswitch setup for the given arch"
    echo " -v|--verbose\t\tverbosity"
	exit 1
}

info() {
	echo "Setup is for arch $CROSS_ARCH"
	echo "Sysroot is $CROSS_ROOT"
	echo "Rpm macros are overriten from this is /etc/rpm/$arch-linux"
}

reset_native() {
	echo "Reset environment for x86_64"
	exec -lc bash
	exit 0
}

switch_arch() {
	local arch=$1
	[ -z $arch ] && error "No arch given for switch_arch"
	[[ "$arch" == "x86_64" ]] && reset_native

	local source_file=/usr/$arch-linux-gnu/bin/cross-profile-setup-sdk-$arch.sh
	[ -f source_file ] || error "No file $source_file, arch=$arch is unknow"

	echo "Sourcing file $source_file, \$PATH is prepend with /usr/bin/cross-wrappers"
	source $source_file

	echo "Setup is done for $arch, used sysroot is $CROSS_ROOT"
	exit 0
}

while [ $# -ne 0 ]; do
    case $1 in
        -i|--info)
            info
            ;;
        -s | --switch-arch)
            shift
			switch_arch $1
            ;;
        -v | --verbose)
            VERBOSE=1
            ;;
        -h|--help)
            usage
            ;;
        *)
            usage
            ;;
    esac
    shift
done
