#!/bin/bash

set -e

working_dir=$(pwd)
script_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]:-$0}"; )" &> /dev/null && pwd 2> /dev/null; )";

# Create a temporary directory
tmp_dir=$(mktemp -d "${TMPDIR:-/tmp/}generate-typescript.XXXXXXXXX")
cd $tmp_dir

# Copy the parse script into the temp directory
cp -r $script_dir/* .

spec_path=''
output_path=''
package_name=''
while [[ "$#" -gt 0 ]]; do case $1 in
  --spec-path) spec_path="$2"; shift;;
  --output-path) output_path="$2"; shift;;
  --package-name) package_name="$2"; shift;;
esac; shift; done

# Prefer pnpm if available, otherwise fall back to npm so as not to require it as a system-wide dependency
pkg_manager=pnpm
if ! command -v pnpm &> /dev/null; then
  pkg_manager=npm
fi

# Install dependencies
$pkg_manager install --silent --save-dev @openapitools/openapi-generator-cli@2.5.1

# Run the generator
npx openapi-generator-cli generate \
  --log-to-stderr \
  --generator-name typescript-fetch \
  --skip-operation-example \
  --generate-alias-as-model \
  --minimal-update \
  --template-dir templates \
  --config config.yaml \
  --additional-properties=npmName=$package_name,typescriptThreePlus=true,useSingleParameter=true,supportsES6=true \
  --input-spec $spec_path \
  --output $output_path

# Clean up
cd $working_dir
rm -rf $tmp_dir
