#!/bin/bash
#
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Copyright (C) 2024 Guillaume Tucker

set -e

jsonfile="${1}"
opt="${2}"

if [ -z "$jsonfile" ]; then
    echo "Retrieving latest OpenAPI JSON data..."
    curl -s http://localhost:8000/latest/openapi.json > frontend/openapi.json
else
    cp $jsonfile frontend/openapi.json
fi


path=frontend/src/client
git rm -rf --ignore-unmatch ${path}
rm -rf ${path}

img="node:$(cat frontend/.nvmrc)"
docker run \
       -v $PWD:/home/renelick/src \
       -w /home/renelick/src/frontend \
       -u node \
       $img \
       /bin/bash -c "\
node modify-openapi-operationids.js &&
npm install &&
npm run generate-client
"

for p in frontend/patches/*; do
    echo "Applying $p"
    git apply "$p"
done

git add ${path}

stat=$(git diff --cached --stat)
if [ -n "$stat" ]; then
    if [ "$opt" == "commit" ]; then
        if [ -n "$jsonfile" ]; then
            filename=$(basename ${jsonfile})
        else
            filename=openapi.json
        fi
        git commit -sm "frontend: generate client from ${filename}"
    else
        echo "Client updated and ready for commit"
    fi
else
    echo "No changes"
fi

rm -f frontend/openapi.json

exit 0
