#!/bin/bash

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

clean() {
    echo "espdl clean"
    rm -rf "./third_party/source/esp-dl"
}

sync() {
    echo "espdl sync"
    mkdir -p "./third_party/source/esp-dl/esp-dl/fbs_loader"
    curl --silent --show-error --location --output "./third_party/source/esp-dl/esp-dl/fbs_loader/espdl.fbs" "https://github.com/espressif/esp-dl/raw/refs/heads/master/esp-dl/fbs_loader/espdl.fbs"
}

schema() {
    echo "espdl schema"
    [[ $(grep -U $'\x0D' ./source/espdl-schema.js) ]] && crlf=1
    node ./tools/flatc.js --root espdl --out ./source/espdl-schema.js ./third_party/source/esp-dl/esp-dl/fbs_loader/espdl.fbs
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/espdl-schema.js ./source/espdl-schema.js
    fi
}

metadata() {
    echo "espdl metadata"
    if [[ $(grep -U $'\x0D' ./source/espdl-metadata.json) ]]; then crlf=1; else crlf=; fi
    node ./tools/espdl-script.js
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/espdl-metadata.json ./source/espdl-metadata.json
    fi
}

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