#!/bin/sh

# The init function installs necessary dependencies for the script to run correctly.
# If the system is running on Alpine Linux, it updates the package index and installs npm and netcat-openbsd.
init() {
  if [ -f /etc/alpine-release ]; then
    apk add npm netcat-openbsd curl
  fi
}

# The mockFn function starts the mock server using the Stoplight Prism CLI tool.
# It first calls the init function to ensure all dependencies are installed, then runs the mock server on port 4010.
# It will wait until the server is up and running by continuously checking for a successful connection to localhost on port 4010.
mockFn() {
  init
  npx @stoplight/prism-cli -p 4010 mock $SPEC_PATH &
  until nc -z localhost 4010; do sleep 1; done
}

# The proxyFn function starts the proxy server using the Stoplight Prism CLI tool.
# It first calls the init function to ensure all dependencies are installed, then runs the proxy server on port 4010.
# The --errors flag is used to throw errors if requests and responses violate the OpenAPI specs.
# It will wait until the server is up and running by continuously checking for a successful connection to localhost on port 4010.
proxyFn() {
  init
  # Download the spec file using curl
  curl -fsS -o spec.yaml $SPEC_PATH
  if [ $? -ne 0 ]; then
    echo "Error: Failed to download the spec file from $SPEC_PATH."
    exit 1
  fi

  # Run Prism proxy using the downloaded spec file
  npx @stoplight/prism-cli --errors -p 4010 proxy spec.yaml $DOMAIN_PATH &
  until nc -z localhost 4010; do sleep 1; done
}

# The stopFn function stops the server running on port 4010.
# It uses the `lsof` command to find the PIDs of all processes using port 4010 and kills them using `kill`.
stopFn() {
  kill $(lsof -t -i :4010)
}

case "$1" in
mock)
  mockFn
  ;;
proxy)
  proxyFn
  ;;
stop)
  stopFn
  ;;
*)
  echo "Usage: $0 {proxy|mock}"
  exit 1
  ;;
esac

