#!/usr/bin/env bash
# Copyright 2024 The KubeEdge Authors.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail

# Define root and output directories
KUBEEDGE_ROOT=$(unset CDPATH && cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)
OUTPUT_DIR="${KUBEEDGE_ROOT}/apidoc/generated"

# Install openapi-gen tool
if [ "$(which openapi-gen)" == "" ]; then
    echo "Start to install openapi-gen tool"
    GO111MODULE=on go install k8s.io/kube-openapi/cmd/openapi-gen
    GOPATH="${GOPATH:-$(go env GOPATH)}"
    export PATH=$PATH:$GOPATH/bin
fi

# Check and create output directory
if [[ ! -d "${OUTPUT_DIR}" ]]; then
    mkdir -p "${OUTPUT_DIR}"
fi

# Run openapi-gen to generate files
echo "Generating with openapi-gen..."
openapi-gen \
    --input-dirs "github.com/kubeedge/api/apis/apps/v1alpha1" \
    --input-dirs "github.com/kubeedge/api/apis/policy/v1alpha1" \
    --input-dirs "github.com/kubeedge/api/apis/devices/v1alpha2" \
    --input-dirs "github.com/kubeedge/api/apis/devices/v1beta1" \
    --input-dirs "github.com/kubeedge/api/apis/operations/v1alpha1" \
    --input-dirs "github.com/kubeedge/api/apis/reliablesyncs/v1alpha1" \
    --input-dirs "github.com/kubeedge/api/apis/rules/v1" \
    --input-dirs "k8s.io/api/rbac/v1" \
    --input-dirs "k8s.io/api/core/v1" \
    --input-dirs "k8s.io/apimachinery/pkg/apis/meta/v1" \
    --input-dirs "k8s.io/apimachinery/pkg/runtime" \
    --input-dirs "k8s.io/apimachinery/pkg/version" \
    --input-dirs "k8s.io/apimachinery/pkg/api/resource" \
    --output-base "${KUBEEDGE_ROOT}/apidoc/generated"\
    --output-package "openapi" \
    --go-header-file "${KUBEEDGE_ROOT}/apidoc/tools/boilerplate/boilerplate.txt" \
    --output-file-base "zz_generated.openapi"\
	  --v "9"

# Remove specific comments from generated files
find "${OUTPUT_DIR}" -name "zz_generated.openapi.go" -exec sed -i '/^\/\/go:build !ignore_autogenerated$/d' {} \;
find "${OUTPUT_DIR}" -name "zz_generated.openapi.go" -exec sed -i '/^\/\/ +build !ignore_autogenerated$/d' {} \;
