#!/usr/bin/env bash

set -euo pipefail

RUST_ALL_TARGETS=(
    "changeset"
    "config"
    "config-derive"
    "coordinates"
    "cyberpunk-splash"
    "dashboard"
    "emseries"
    "file-service"
    "fitnesstrax"
    "fluent-ergonomics"
    "geo-types"
    "gm-control-panel"
    "hex-grid"
    "ifc"
    "kifu-core"
    "kifu-gtk"
    "memorycache"
    "nom-training"
    "result-extended"
    "screenplay"
    "sgf"
    "tree"
)

build_rust_targets() {
    local CMD=$1
    local TARGETS=${@/$CMD}

    for target in $TARGETS; do
        MODULE=$target CMD=$CMD ./builders/rust.sh
    done
}

build_dist() {
    local TARGETS=${@/$CMD}

    for target in $TARGETS; do
        if [ -f $target/dist.sh ]; then
            build_rust_targets release ${TARGETS[*]}
            cd $target && ./dist.sh
        fi
    done
}

export CARGO=`which cargo`

if [ -z "${TARGET-}" ]; then
    TARGET="all"
fi

if [ -z "${CMD-}" ]; then 
    CMD="test release"
fi

if [ "${CMD}" == "clean" ]; then
    cargo clean
    exit 0
fi

for cmd in $CMD; do
    if [ "${CMD}" == "dist" ]; then
        build_dist $TARGET
    elif [ "${TARGET}" == "all" ]; then
        build_rust_targets $cmd ${RUST_ALL_TARGETS[*]}
    else
        build_rust_targets $cmd $TARGET
    fi
done
