#!/bin/bash

set -e

# Parse arguments
spec_path=''
output_path=''
smithy_json_path=''
while [[ "$#" -gt 0 ]]; do case $1 in
  --spec-path) spec_path="$2"; shift;;
  --output-path) output_path="$2"; shift;;
  --smithy-json-path) smithy_json_path="$2"; shift;;
esac; shift; done

working_dir=$(pwd)
script_dir="$( cd -- "$(dirname $([ -L "${BASH_SOURCE[0]:-$0}" ] && readlink -f "${BASH_SOURCE[0]:-$0}" || echo "${BASH_SOURCE[0]:-$0}"))" >/dev/null 2>&1 ; pwd -P )";

# load common package manager helper functions
. "$script_dir/../common/common.sh"

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

log "parse-openapi-spec :: tmp_dir :: $tmp_dir"

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

# Install dependencies
install_packages

# Run the parse script
run_command ts-node parse-openapi-spec.ts \
  --specPath="$working_dir/$spec_path" \
  --outputPath="$working_dir/$output_path" \
  ${smithy_json_path:+"--smithyJsonPath=$working_dir/$smithy_json_path"}

echo "openapi-spec parsed"

# Clean up
cd $working_dir
rm -rf $tmp_dir
