# Build script for adjust the toolchain.
#
# Copyright (C) 2014-2017, 2020-2021 Matias Fonzo, <selk@dragora.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This will be handled by libs/musl (post-install script):

cat << EOF > /tools/bin/adjust-toolchain
#! /bin/sh -

if test -r /tools/bin/ld-new
then
    set -e
    echo "\${0}: Adjusting toolchain ..."
    set -x

    CC=gcc
    TRIPLET="\$(\$CC -dumpmachine)"
    libSuffix=$libSuffix

    mv /tools/bin/ld /tools/bin/ld-old
    mv /tools/\${TRIPLET}/bin/ld /tools/\${TRIPLET}/bin/ld-old
    mv /tools/bin/ld-new /tools/bin/ld
    ln -sf /tools/bin/ld /tools/\${TRIPLET}/bin/ld

    \$CC -dumpspecs | sed \\
     -e 's@/tools@@g' \\
     -e "/\*startfile_prefix_spec:/{n;s@.*@/usr/lib\${libSuffix}/ @}" \\
     -e '/\*cpp:/{n;s@\$@ -isystem /usr/include@}' \\
      > "\$(dirname -- "\$(\$CC --print-libgcc-file-name)")"/specs
fi

EOF

chmod 700 /tools/bin/adjust-toolchain

