#!/bin/bash
set -eou pipefail


if [[ "${OSTYPE}" == "darwin"* ]]; then
    if ! which buf &>/dev/null; then brew install buf; fi
    if ! which shellcheck &>/dev/null; then brew install shellcheck; fi
    if ! which markdownlint &>/dev/null; then brew install markdownlint-cli; fi
    if ! java -version &>/dev/null; then
        brew install java
        sudo ln -sfn /opt/homebrew/opt/openjdk/libexec/openjdk.jdk \
            /Library/Java/JavaVirtualMachines/
    fi
    if ! kotlinc -version &>/dev/null; then brew install kotlin; fi
    if ! swiftformat -version &>/dev/null; then brew install swiftformat; fi
    if ! which foundryup &>/dev/null; then
        # install foundry for tests that require mocking blockchain
        curl -L https://foundry.paradigm.xyz | bash
        # you may need to adjust this depending on which $SHELL you use
        source "$HOME"/.zshenv
        foundryup
    fi
    if ! wasm-pack --version &>/dev/null; then cargo install wasm-pack; fi
    if ! cargo llvm-cov --version &>/dev/null; then cargo install cargo-llvm-cov; fi
fi

if command -v rustup >/dev/null 2>&1; then
  rustup update
else
    echo "rustup is not installed, rust may not be up to date"
fi

WASM_TARGET="wasm32-unknown-unknown"

if [ ! -d "$(rustc --print sysroot)/lib/rustlib/$WASM_TARGET" ]; then
    echo "✗ $WASM_TARGET is not installed"
    echo "Installing $WASM_TARGET..."

    if rustup target add "$WASM_TARGET"; then
        echo "✓ Successfully installed $WASM_TARGET"
    else
        echo "✗ Failed to install $WASM_TARGET"
        exit 1
    fi
else
    echo "✓ $WASM_TARGET is already installed"
fi

dev/build_validation_service_local
dev/docker/up
