#!/usr/bin/env bash

build_binaries() {
    CARGO_BUILD_TARGET_DIR=$(mktemp --tmpdir --directory)
    for arch in x86_64-unknown-linux-gnu x86_64-unknown-linux-musl aarch64-unknown-linux-gnu aarch64-unknown-linux-musl x86_64-unknown-freebsd; do
        if cross build --target="$arch" --target-dir="$CARGO_BUILD_TARGET_DIR" --release; then
            mv "$CARGO_BUILD_TARGET_DIR"/"$arch"/release/bibiman ./binary-files/bibiman-"$arch"
        else
            echo "Couldn't build for architecture \'$arch\'."
        fi
    done

    rm -rf "$CARGO_BUILD_TARGET_DIR"
}

manpages() {
    bibiman_version=$(grep "^version =" Cargo.toml | cut -d'"' -f2)
    for man_md in ./man/*.md; do
        sed -i -E "s/bibiman [0-9]+\.[0-9]+\.[0-9]+/bibiman $bibiman_version/g" "$man_md"
        sed -i -E "s/date: .*/date: $(date +%Y-%m-%d)/g" "$man_md"
        man_name="$(basename --suffix=.md "$man_md")"
        pandoc -s --from=markdown --to=man "$man_md" -o ./man/"$man_name"
    done
}

if [[ $# -eq 1 ]]; then
    case "$1" in
    "--man" | "-m")
        echo "Building only the manpages"
        manpages
        ;;
    "--all" | "-a")
        echo "Building binaries"
        build_binaries

        echo "Building manpages"
        manpages
        ;;
    *)
        echo "Invalid argument: $1"
        echo "Use --man to build only manpages."
        echo "Use --all or no args to build binaries and manpages"
        exit 1
        ;;
    esac
elif [[ $# -eq 0 ]]; then
    echo "Building binaries"
    build_binaries

    echo "Building manpages"
    manpages
else
    echo "Use --man to build only manpages."
    echo "Use --all or no args to build binaries and manpages"
    exit 1
fi
