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

set -e

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

jsontemp=

if [ -z "$jsonfile" ]; then
    jsontemp=$(mktemp -p .)
    jsonfile=${jsontemp}
    echo "Retrieving latest OpenAPI JSON data..."
    curl -s http://localhost:8000/latest/openapi.json > ${jsonfile}
fi

path=renelick/client/openapi
git rm -rf --ignore-unmatch ${path}
rm -rf ${path}

docker \
    run \
    -v $PWD:/home/renelick/src \
    --entrypoint=/bin/bash \
    renelick \
    -c "\
openapi-python-client \
generate \
--output-path=/home/renelick/src/${path} \
--meta=none \
--config=/home/renelick/src/openapi/client.yaml \
--path=/home/renelick/src/${jsonfile}"

git add ${path}/types.py
git add ${path}/models
rm -rf ${path}/api
rm -f ${path}/client.py
rm -f ${path}/errors.py
echo -n > ${path}/__init__.py
git add ${path}/__init__.py

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

[ -n "${jsontemp}" ] && rm ${jsontemp}

exit 0
