#!/bin/bash
set -o pipefail

script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
msh_home=`realpath $script_dir/..`

source "$msh_home/lib/defaults.cf"
[ -f "$msh_home/etc/config.cf" ] && source "$msh_home/etc/config.cf"
source "$msh_home/lib/functions.sh"

mkdir -p "$msh_home/var/log"

# Log file for this launcher. Lines emitted via log_info/log_error also go to the
# systemd journal, so they show up in `systemctl status` / `journalctl`.
MSH_LOG_FILE="$msh_home/var/log/web.out"
: > "$MSH_LOG_FILE"

# Resolve the shared database path (relative path is taken from the install dir).
case "$DB_FILENAME" in
  /*) db_path="$DB_FILENAME" ;;
  *)  db_path="$msh_home/$DB_FILENAME" ;;
esac
mkdir -p "$(dirname "$db_path")"

# Optional HTTPS: enabled only when a keystore is configured and present.
ssl_args=()
if [ -n "$WEB_SSL_KEYSTORE" ]; then
  case "$WEB_SSL_KEYSTORE" in
    /*) keystore_path="$WEB_SSL_KEYSTORE" ;;
    *)  keystore_path="$msh_home/$WEB_SSL_KEYSTORE" ;;
  esac
  if [ -f "$keystore_path" ]; then
    ssl_args=(
      --server.ssl.enabled=true
      --server.ssl.key-store="$keystore_path"
      --server.ssl.key-store-password="$WEB_SSL_KEYSTORE_PASSWORD"
      --server.ssl.key-store-type="${WEB_SSL_KEYSTORE_TYPE:-PKCS12}"
      --server.ssl.key-alias="${WEB_SSL_KEY_ALIAS:-msh-zr-web}"
    )
  else
    log_error "WEB_SSL_KEYSTORE is set to '$keystore_path' but no such file exists; starting on HTTP."
  fi
fi

# 1) Verify Java executable
if [ -z "$MSH_JAVA_BIN" ]; then
  log_error "MSH_JAVA_BIN is not set!"
  sleep 1
  exit 1
fi

java_bin=""
if [ -x "$MSH_JAVA_BIN" ]; then
  java_bin="$MSH_JAVA_BIN"
else
  java_bin="$(command -v "$MSH_JAVA_BIN" 2>/dev/null || true)"
fi

if [ -z "$java_bin" ] || [ ! -x "$java_bin" ]; then
  log_error "MSH_JAVA_BIN ('$MSH_JAVA_BIN') does not point to a valid executable."
  sleep 1
  exit 1
fi

# 2) Check Java version is at least 21
ver_output="$("${java_bin}" -version 2>&1 || true)"
version_str="$(printf '%s\n' "$ver_output" | head -n1 | sed -E 's/.*version "([^"]+)".*/\1/')"

if [[ -z "${version_str}" ]]; then
  log_error "Unable to determine Java version from: ${ver_output}"
  sleep 1
  exit 1
fi

if [[ "${version_str}" == 1.* ]]; then
  major_ver="$(printf '%s' "${version_str}" | cut -d. -f2)"
else
  major_ver="$(printf '%s' "${version_str}" | cut -d. -f1)"
fi

# Ensure major_ver is numeric
if ! [[ "${major_ver}" =~ ^[0-9]+$ ]]; then
  log_error "Unrecognized Java version: ${version_str}"
  sleep 1
  exit 1
fi

if (( major_ver < 21 )); then
  log_error "Java ${version_str} detected. Java 21+ is required."
  sleep 1
  exit 1
fi

if ! "$java_bin" -version >/dev/null 2>&1; then
  log_error "Failed to execute '$java_bin -version'. Please check your Java installation."
  sleep 1
  exit 1
fi

# Run the web app. Combined output goes to the systemd journal (so errors show in
# `systemctl status`) and is appended to the log file via tee.
"$java_bin" \
-Xms$JAVA_XMS \
-Xmx$JAVA_XMX \
-Dfile.encoding=UTF8 \
-jar "$msh_home/bin/jar/msh-zr-web.jar" \
--server.port=$WEB_PORT \
--msh.zr.install.dir="$msh_home" \
--msh.zr.db.path="$db_path" \
--msh.zr.logs.path="$msh_home/var/log" \
"${ssl_args[@]}" \
$@ \
2>&1 | tee -a "$MSH_LOG_FILE"
