#!/bin/bash
# mer-tooling-chroot - chroot into a Mer SDK tooling

set -u
set -e

CHROOT_ARCH=i386

usage() {
    cat <<EOF
usage: $0 [<command> <args>...]
       $0 -h

    $0 - chroot into a Mer SDK tooling.

    Options:

     <command> [<args>...]  If present the given command will be executed
                            instead of a login shell
     -h                     Show this help

EOF
    return 0
}

while getopts "h" opt; do
    case $opt in
        h ) usage
            exit;;
        \? ) usage
            exit 1;;
    esac
done
shift $(($OPTIND - 1))

if [[ ! -f /etc/MerSDK ]]; then
    echo "$0 cannot be run outside the SDK; exiting"
    exit 1
fi

if [[ $EUID -ne 0 ]]; then
    exec sudo $0 "$@"
    echo "$0 must be run as root and sudo failed; exiting"
    exit 1
fi

toolingroot=$(dirname $(readlink -f $0))

if [[ ! -f ${toolingroot}/etc/SDKTooling ]] ; then
    echo "${toolingroot} does not look like a Mer SDK tooling root."
    exit 1
fi

################################################################

prepare_etc() {
    cp --remove-destination --dereference /etc/resolv.conf ${toolingroot}/etc/resolv.conf

    cat >${toolingroot}/etc/profile.d/90_prompt.sh <<END
# Do not edit! Created by /$(basename $0)
PS1="($(basename ${toolingroot}) tooling) \$PS1"
END
}

detect_chroot_arch() {
    ld_name=$(find /lib/ld-linux* -printf "%f\n")
    if [[ "${ld_name}" == ld-linux-x86-64* ]]; then
        CHROOT_ARCH=x86_64
    fi
}

################################################################

prepare_etc
detect_chroot_arch

if [[ $# -ne 0 ]]; then
    setarch "${CHROOT_ARCH}" chroot ${toolingroot} "${@}"
else
    setarch "${CHROOT_ARCH}" chroot ${toolingroot} /bin/bash --login
fi
