#!/usr/bin/env bash
#
# crossclang
# A helper script to simplify cross-compilation
#
# ld64shim can fix some issues at link-time.
#
# Copyright 2021 Christian Kohlschütter
#
# 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.
#

printHelp=0

linker="ld64.lld"
linkerArgs=()

llvmPath=
llvmName=llvm
latestLLVM=$(shopt -u failglob ; for f in {/usr/local,/opt/homebrew}/Cellar/"$llvmName"/*/bin; do [[ -d "$f" ]] && echo $f; done | sort -r -n | head -n 1)
if [[ -n "$latestLLVM" && -d "$latestLLVM" ]]; then
    llvmPath="$latestLLVM"
fi

linkerPath="$(PATH=/usr/bin:$PATH:$llvmPath which ${linker[@]} 2>/dev/null | head -n 1)"
if [ ! -f "$linkerPath" ]; then
    echo "Cannot find linker: ${linker[@]}" >&2
    exit 1
fi

skipPlatformVersion=0
linkerVersion=$("$linkerPath" --version 2>/dev/null)
if [[ -z $linkerVersion ]]; then
    # Change https://reviews.llvm.org/D97799 landed in llvm 13
    # llvm 12 and older don't support "ld64.lld --version", which makes this an easy check
    skipPlatformVersion=1
fi

while [[ $# -gt 0 ]]; do
    v="$1"
    shift

    case "$v" in 
        -platform_version )
            if [[ $skipPlatformVersion -gt 0 ]]; then
                # ignore this parameter and up to three arguments on older releases only
                # see https://github.com/Homebrew/homebrew-core/issues/52461
                # see https://reviews.llvm.org/D97799
                for i in 1 2 3; do
                    [[ $1 =~ ^- ]] && break
                    shift
                done
                continue
            fi
        ;;
    esac

    linkerArgs+=("$v")
done

if [ $printHelp -eq 1 ]; then
    cat <<EOT
Syntax: $0 [--help|-h]
           -- <linker opts>...
EOT
    exit 1
fi

exec "$linkerPath" ${linkerArgs[@]}
