#!/bin/bash

# cd into the directory containing this script (from the bash faq 028)
if [[ $BASH_SOURCE = */* ]]; then
  cd -- "${BASH_SOURCE%/*}/" || exit
fi

cd ..

fetch_repo() {
    repo_url="$1"
    commit_id="$2"
    dir_name="$3"
    update_crate="$4"

    if [ -d "$dir_name" ]; then
        ( cd "$dir_name" && git fetch origin --tags && \
            git checkout "$commit_id" )
    else
        git clone "$repo_url" "$dir_name" && \
        ( cd "$dir_name" && git checkout "$commit_id" && \
            # Patch the Cargo.toml files to point to the local copies
            # of our own sigma-rs dependencies
            if [ -e "../patches/${dir_name}.diff" ]; then
                patch -p1 < ../patches/${dir_name}.diff || exit 1
            fi )
    fi
    # Update the Cargo.lock file to catch the now-local sigma-rs dependencies
    if [ "$update_crate" != "" ]; then
        ( cd "$dir_name" && cargo update "$update_crate" ) || exit 1
    fi
}

fetch_repos() {
    fetch_repo https://github.com/arkworks-rs/spongefish v0.6.1 spongefish && \
    fetch_repo https://github.com/mmaker/sigma-rs v0.3.1 sigma-proofs spongefish && \
    fetch_repo https://git-crysp.uwaterloo.ca/SigmaProtocol/sigma-compiler 0.2.2 sigma-compiler sigma-proofs && \
    fetch_repo https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz 0.2.1 cmz sigma-compiler && \
    fetch_repo https://gitlab.torproject.org/onyinyang/lox.git/ lox-artifact application-lox cmz && \
    fetch_repo https://gitlab.torproject.org/onyinyang/lox.git/ lox-artifact-zkp application-lox-zkp && \
    fetch_repo https://github.com/ooni/userauth artifact-v0.4 application-ooni cmz
}

fetch_repos
