#!/usr/bin/env bash
set -euo pipefail

# This file simply runs an http server locally and watches for changes in extensions to update the index.
# Requires java to be installed.
# Defaults to hosting on: http://localhost:8000

# How to use:
# 1. Run this script
# 2. Ensure the <your-ip>:8000 is in your Shosetsu installation's repository list
# 3. Make your changes to the extensions
# 4. Reload the repository list in Shosetsu
# 5. Test your changes
# 6. Repeat steps 3-5 as needed

# Ensure that java is available and the extension-tester.jar is downloaded
if command -v java &> /dev/null; then
  _java=$(command -v java)
elif [ -n "${JAVA_HOME:-}" ] && [ -x "$JAVA_HOME/bin/java" ]; then
  _java="$JAVA_HOME/bin/java"
else
  echo "java not found. Please ensure you have an up-to-date version of java installed and in your PATH."
  exit 1
fi
if [ ! -f bin/extension-tester.jar ]; then
  echo "extension-tester.jar not found. Running dev-setup.sh to download it."
  ./dev-setup.sh --tester
fi

# Ensure java version is at least 21
_java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F '.' '{sub("^$", "0", $2); print $1$2}')
if [ "$_java_version" -lt 210 ]; then
  echo "java version is less than 21. Please update your java installation."
  exit 1
fi

# Start the index generation/http server
exec java -jar bin/extension-tester.jar --generate-index --watch --host
