#!/bin/bash
# Test building each of the wasm targets.
set -euox pipefail

RUST_VERSION=$(dpkg-parsechangelog -SVersion | sed -re 's/([^.]+)\.([^.]+)\..*/\1.\2/')

# Set RUSTC so that `cargo` knows which rustc to use
export RUSTC=/usr/lib/rust-${RUST_VERSION}/bin/rustc
CARGO=/usr/lib/rust-${RUST_VERSION}/bin/cargo

tmpdir=$(mktemp -d)
cd "$tmpdir"

${CARGO} new hello
cd hello

cat <<EOF >src/main.rs
use anyhow::Result;

fn main() -> Result<()> {
    println!("Hello, World!");
    Ok(())
}
EOF

${CARGO} add 'anyhow@^1'
${CARGO} vendor

mkdir -p .cargo
cat <<EOF >.cargo/config.toml
[source.crates-io]
replace-with = "vendored-sources"

[source.vendored-sources]
directory = "vendor"
EOF

# wasm32-unknown-unknown and wasm32-wasip1 use `rust-lld` as their default
# linker, which is not guaranteed to be installed under that name, so use
# the versioned LLVM wasm linker instead.
wasm_ld=/usr/bin/wasm-ld-22
export CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_LINKER="$wasm_ld"
export CARGO_TARGET_WASM32_WASIP1_LINKER="$wasm_ld"

# wasm32-wasip2 uses wasm-component-ld as its outer linker, which in turn by default
# searches PATH for `wasm-ld` or `rust-lld`. Neither unversioned name is guaranteed
# to be installed, so pass the versioned wasm linker explicitly.
export CARGO_TARGET_WASM32_WASIP2_RUSTFLAGS="-C link-arg=--wasm-ld-path=$wasm_ld"

rc=0
for target in wasm32-unknown-unknown wasm32-wasip1 wasm32-wasip2; do
    if ! ${CARGO} build --target "$target"; then
        echo "$target build failed" >&2
        rc=1
    fi
done
exit $rc
