#!/bin/bash

# --------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Generate C# API Client using OpenAPI Generator:
# --------------------------------------------------------------------------------------------------------------------------------------------------------------------
# This script generates a C# API client based on the OpenAPI specification.
#
# The actions performed are:
# - Generating the API client code using podman (make sure it's available).
# - Deleting existing API client source files.
# - Copying the newly generated API client source to the project directory.
# - Updating the docs.
# - Replacing the README.md file.
# - Cleaning up temporary files.
#
# Defined variables:
OUTPUT_DIR="temp"                                     # The temporary directory for generated files
ARTIFACT_ID="Coscine.ApiClient.Core"                  # The artifact ID for the API client
PACKAGE_NAME="Coscine.ApiClient.Core"                 # The package name for the API client
API_SPEC_URL="https://coscine-api-hristov.web.vulcanus.otc.coscine.dev/coscine/api/swagger/v2/swagger.json" # URL to the OpenAPI spec file
# --------------------------------------------------------------------------------------------------------------------------------------------------------------------

# ANSI color codes for styling
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Run the OpenAPI generator
echo -e "${CYAN}Running the OpenAPI generator...${NC}"
podman run --rm \
  -v ${PWD}:/local openapitools/openapi-generator-cli generate \
  -i "$API_SPEC_URL" \
  -g csharp \
  -o /local/$OUTPUT_DIR \
  --artifact-id "$ARTIFACT_ID" \
  --package-name "$PACKAGE_NAME" \
  --skip-validate-spec \
  --server-variables=host=localhost:5000,basePath=coscine \
  --additional-properties=targetFramework=net8.0

echo -e "${GREEN}API client generation complete.${NC}"

# Delete the current API client source
echo -e "${YELLOW}Deleting current API client source...${NC}"
rm -rf "src/$PACKAGE_NAME"
rm -rf "src/${PACKAGE_NAME}.Test"

# Delete the current docs directory
echo -e "${YELLOW}Deleting current docs directory...${NC}"
rm -rf "docs"

# Copy the generated API client source to the src directory
echo -e "${CYAN}Copying generated API client source to src directory...${NC}"
cp -R "$OUTPUT_DIR/src/$PACKAGE_NAME" "src/$PACKAGE_NAME"
cp -R "$OUTPUT_DIR/src/${PACKAGE_NAME}.Test" "src/${PACKAGE_NAME}.Test"

# Copy the generated docs to the docs directory
echo -e "${CYAN}Copying generated docs to docs directory...${NC}"
cp -R "$OUTPUT_DIR/docs" "docs"

# Replace the README.md file
echo -e "\n${CYAN}Replacing README.md file...${NC}"
cp "$OUTPUT_DIR/README.md" "README.md"

# Remove the temp directory
echo -e "${YELLOW}Cleaning up...${NC}"
rm -rf "$OUTPUT_DIR"

echo -e "${GREEN}Finished.${NC}"