#!/bin/bash

set -e
pushd $(cd $(dirname ${0})/..; pwd) > /dev/null

src_dir=./third_party/source/jax

clean() {
    echo "jax clean"
    rm -rf "${src_dir}"
}

sync() {
    echo "jax sync"
    mkdir -p "${src_dir}/jax/_src/export"
    curl --silent --show-error --location --output "${src_dir}/jax/_src/export/serialization.fbs" "https://github.com/jax-ml/jax/raw/main/jax/_src/export/serialization.fbs"
}

schema() {
    echo "jax schema"
    [[ $(grep -U $'\x0D' ./source/jax-schema.js) ]] && crlf=1
    node ./tools/flatc.js --root jax --out ./source/jax-schema.js --path "${src_dir}" ${src_dir}/jax/_src/export/serialization.fbs
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/jax-schema.js ./source/jax-schema.js
    fi
}

while [ "$#" != 0 ]; do
    command="$1" && shift
    case "${command}" in
        "clean") clean;;
        "sync") sync;;
        "schema") schema;;
    esac
done
