#!/bin/bash

: '
# Rust Project Builder Assistant

> A new cool Rust project building attitude

What I do for you:
+ launch tests if asked with allowed prints
+ build your project in `debug` or `release` and create a binary file with the name of the field `name` in your `Cargo.toml`
+ bring your compiled binary to the project root automatically, wheter you build in `debug` or `release`
+ strip the binary to make is lighter
+ simplify the addition of `RUSTFLAGS` compiler options

## Required

TOML parser [stoml](https://github.com/freshautomations/stoml)

## Installation

```bash
chmod +x compile.sh
```

## Usage

This command calls `Cargo build`:

```bash
./compile [ARGS]
```

Optional ARGS:
+ `-t` or `--test`: to launch tests
+ `-r` or `--release`: to build in release (otherwise by default it builds in `debug`)

You can also change the variable `CUSTOM_RUSTFLAGS` in the comment section `# parameters` to add compilation options (such as ignoring `dead_code`)

'

set -e

# parameters
# CUSTOM_RUSTFLAGS="dead_code unused_variables unused_imports"

# other variables
NAME=`stoml Cargo.toml package.name`
OUTDIR="."
FLAGS=""
BUILD=""
export RUST_BACKTRACE=1

# parse command line arguments
OPTIONS=rt
LONGOPTS=release,test
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
eval set -- "$PARSED"
r=n t=n
while true; do
    case "$1" in
        -r|--release) r=y; shift;;
        -t|--test) t=y; shift;;
        --) shift; break;;
        *) echo "Argument error"; exit 3;;
    esac
done

# launch tests
if [ "$t" == y ]; then
    cargo test
    exit 0;
fi

# parse build option: release or debug
[[ "$r" == y ]] && BUILD="release" && FLAGS+="--release " || BUILD="debug"

# add "-A " option before every CUSTOM_RUSTFLAGS
ARRAY_CUSTOM_RUSTFLAGS=($CUSTOM_RUSTFLAGS)
ARRAY_CUSTOM_RUSTFLAGS_WITH_OPTION=("${ARRAY_CUSTOM_RUSTFLAGS[@]/#/-A }")
CUSTOM_RUSTFLAGS_WITH_OPTION=$( IFS=$' '; echo "${ARRAY_CUSTOM_RUSTFLAGS_WITH_OPTION[*]}" )

# build
RUSTFLAGS="$RUSTFLAGS $CUSTOM_RUSTFLAGS_WITH_OPTION" cargo build $FLAGS

# move binary to OUTDIR and strip it
cp target/$BUILD/$NAME $OUTDIR
strip $OUTDIR/$NAME

# execute the binary
$OUTDIR/$NAME
