#! /bin/bash

# check-cross-arch - check if qemu is needed for the target directory
#
# This script is part of FAI (Fully Automatic Installation)
# Copyright (C) 2017-2020 Thomas Lange, lange@cs.uni-koeln.de

set -euE

verbose=${verbose:-0}
target=$1

# is there already a qemu-*static binary?
if [ -n "$(ls $target/usr/bin/qemu-*-static* 2>/dev/null)" ]; then
    echo qemu user static already available
    exit 1
fi


info=$(file /bin/more)
myarch=$(expr "$info" : '.*ld-linux-\([^[:space:]]*\).so.*')
i386_re="ELF 32-bit LSB (shared object|pie executable), Intel 80386"
if [ -z "$myarch" ]; then
    if [[ "$info" =~  $i386_re ]]; then
	myarch=i386
    fi
fi

# where is the more command
if [ -f $target/bin/more ]; then
    _more=$target/bin/more
elif [ -f $target/usr/bin/more ]; then
    _more=$target/usr/bin/more
else
    echo "Cannot find more command in $target"
    exit 3
fi

_more=$(realpath -m $_more)      # handle symlink
_more=$target/${_more#$target}
info=$(file $_more)
targetarch=$(expr "$info" : '.*ld-linux-\([^[:space:]]*\).so.*') || true
if [ -z "$targetarch" ]; then
    if [[ "$info" =~  $i386_re ]]; then
	targetarch=i386
    fi
fi

cross=1
# debugging echo myarch: $myarch targetarch: $targetarch
if [ $myarch = $targetarch ]; then
    cross=0
fi

for arch in $(dpkg --print-foreign-architectures); do
    if [ $myarch = $arch ]; then
        cross=0
        break
    fi
done


if [ $cross -eq 1 ]; then
     [ X$verbose = X1 ] && echo "Using qemu-$targetarch-static for cross architecture chroot."

     # if the flag F is set, we do not need the static executable inside $target
     if grep -E -q --color '^flags: .*F.*' /proc/sys/fs/binfmt_misc/qemu-$targetarch; then
	 :
     else
	 cp /usr/bin/qemu-$targetarch-static $target/usr/bin
     fi
fi

exit $cross
