#!/usr/bin/env bash

set -e

# map of the URL of the latest version of each ontology in OWL format
# http://edamontology.org/EDAM.owl is not uptodate for 1.25 yet (2020 11 09)
declare -A ONTOLOGY_URLS=( \
    ["edam"]="https://raw.githubusercontent.com/edamontology/edamontology/master/releases/EDAM.owl" \
    ["funderRegistry"]="https://doi.crossref.org/funderNames?mode=list" \
    ["kisao"]="https://raw.githubusercontent.com/SED-ML/KiSAO/deploy/kisao.owl" \
    ["linguist"]="https://raw.githubusercontent.com/jaebradley/github-languages-client/master/src/languages.json" \
    ["sbo"]="https://raw.githubusercontent.com/EBI-BioModels/SBO/master/SBO_OWL.owl" \
    ["sio"]="https://raw.githubusercontent.com/MaastrichtU-IDS/semanticscience/master/ontology/sio/release/sio-release.owl" \
    ["spdx"]="https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json" \
    )

# list of ontologies that needs to be updated
# specified by single command-line argument with comma-separated list of ontology ids
# if no argument is provided, default is to update all ontologies
if [ -z "${1}" ]
then
    read -a ontologies <<< "${!ONTOLOGY_URLS[@]}"
else
    IFS="," read -a ontologies <<< "${1/ /}"
    unset IFS
fi

# sort ontologies
IFS=$'\n' ontologies=($(sort <<<"${ontologies[*]}"))
unset IFS

# print status
echo "Updating ${#ontologies[@]} ontologies."

# location of this script
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# download latest version of each ontology, convert to JSON, and save to this repository
for ontology in "${ontologies[@]}"
do
    # print status
    echo "Updating ${ontology} ..."

    # get URL for raw version of ontology
    ontology_url=${ONTOLOGY_URLS[$ontology]}

    filename=$(basename -- "$ontology_url")
    extension="${filename##*.}"

    if [ "$ontology" = "funderRegistry" ]; then
        temp_file="$(mktemp)"
        wget ${ontology_url} -O ${temp_file}
        csvjson ${temp_file} > ${script_dir}/../libs/ontology/sources/src/lib/${ontology}.json
    elif [ "$extension" = "json" ]; then
        wget ${ontology_url} -O ${script_dir}/../libs/ontology/sources/src/lib/${ontology}.json
    else
        # create temp file for JSON version of ontology
        temp_file="$(mktemp)"

        # convert ontology from OWL to JSON
        java -jar ${script_dir}/GenerateOntology.jar ${ontology_url} ${temp_file}

        # move JSON version of ontology to repo
        mv ${temp_file} ${script_dir}/../libs/ontology/sources/src/lib/${ontology}.json
    fi

    # print status
    echo " done."
done
