#!/bin/bash
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"

mkdir -p "$msh_home/var/log"

# 1) Verify Java executable
if [ -z "$MSH_JAVA_BIN" ]; then
  echo "Error: MSH_JAVA_BIN is not set!" >&2
  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
  echo "Error: MSH_JAVA_BIN ('$MSH_JAVA_BIN') does not point to a valid executable." >&2
  sleep 1
  exit 1
fi

# 2) Check Java version is at least 17
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
  echo "Error: Unable to determine Java version from: ${ver_output}" >&2
  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
  echo "Error: Unrecognized Java version: ${version_str}" >&2
  sleep 1
  exit 1
fi

if (( major_ver < 17 )); then
  echo "Error: Java ${version_str} detected. Java 17+ is required." >&2
  sleep 1
  exit 1
fi

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

"$java_bin" \
-Xms$JAVA_XMS \
-Xmx$JAVA_XMX \
-Dfile.encoding=UTF8 \
-Dinstalldir="$msh_home" \
-jar "$msh_home/bin/jar/msh-pm-milter.jar" \
-milter-port=$MILTER_PORT \
-settings-port-in=$SETTINGS_PORT_IN \
-pool-size=$POOL_SIZE \
-queue-size=$QUEUE_SIZE \
-stats-update-time=$STATS_UPDATE_TIME \
-mail-smtp-port=$MAIL_SMTP_PORT \
$@ \
> "$msh_home/var/log/milter.out" 2>&1