#!/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/}parse-openapi-spec.XXXXXXXXX")
cd $tmp_dir

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

# 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. Note that projen version does not need to be kept in sync with project projen version since
# this runs in isolation.
$pkg_manager install --silent --save-dev \
  typescript@4.7.2 \
  @types/node@14.14.20 \
  ts-node@10.8.1 \
  @apidevtools/swagger-parser@10.0.3 \
  openapi-types@11.0.1 \
  ts-command-line-args@2.3.1 \
  projen@0.57.9

# Run the parse script
npx ts-node parse-openapi-spec.ts "$@"

# Clean up
cd $working_dir
rm -rf $tmp_dir
