#!/bin/bash
#
# Copyright (c) 2023, 2026 Contributors to the Eclipse Foundation
# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v. 2.0, which is available at
# http://www.eclipse.org/legal/epl-2.0.
#
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the
# Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
# version 2 with the GNU Classpath Exception, which is available at
# https://www.gnu.org/software/classpath/license.html.
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
#

startAsMainProcess () {
    if [[ "$@" == "--help" ]] || [[ "$@" == "--help=true" ]] || [[ "$@" == "-?" ]]; then
      exec "$JAVA" ${ASADMIN_JVM_OPTIONS} --module-path "${ASADMIN_MODULEPATH}" --add-modules ALL-MODULE-PATH -cp "$ASADMIN_CLASSPATH" org.glassfish.admin.cli.AsadminMain start-domain --help
    fi

    # Execute start-domain --dry-run and store the output line by line into an array.
    # All lines before and including a line that starts with Dump (Dump of JVM Invocation line...) will be ignored.
    # The last line will not be part of the command to execute, we'll it them later.
    # If command fails, the last item in the array will be "FAILED"
    local DRY_RUN_OUTPUT=()
    local SKIP_LINES_UNTIL_DUMP=y
    local DRY_RUN_OUTPUT_BEFORE_DUMP=
    while IFS= read -r COM; do
      if [[ "$SKIP_LINES_UNTIL_DUMP" == y ]]; then
        if [[ "$COM" == Dump* ]]; then
          SKIP_LINES_UNTIL_DUMP=n
        elif [[ "$COM" != "FAILED" ]]; then
          DRY_RUN_OUTPUT_BEFORE_DUMP+="$COM\n";
        fi
      else
        DRY_RUN_OUTPUT+=("'$COM'");
      fi
    done < <("$JAVA" ${ASADMIN_JVM_OPTIONS} --module-path "${ASADMIN_MODULEPATH}" --add-modules ALL-MODULE-PATH -cp "$ASADMIN_CLASSPATH" org.glassfish.admin.cli.AsadminMain start-domain --dry-run "$@" || echo "FAILED")
    if [[ ${#DRY_RUN_OUTPUT[@]} -eq 0 ]]; then
        echo -n -e "${DRY_RUN_OUTPUT_BEFORE_DUMP}" >&2
        exit 1
    fi
    local OUTPUT_LENGTH=${#DRY_RUN_OUTPUT[@]}

    # If all OK, execute the command to start GlassFish.
    # Remove the last line as it's not part of the command.
    local FINAL_COMMAND=(${DRY_RUN_OUTPUT[@]:0:${OUTPUT_LENGTH}-2})
    eval "exec ${FINAL_COMMAND[@]}"

}

AS_CONFIG="$(dirname "$(realpath "$0")")/../glassfish/config"
AS_CONFIG_SH="${AS_CONFIG}/config.sh"
source "${AS_CONFIG_SH}" "$AS_CONFIG" || { echo "${AS_CONFIG_SH} not found" >&2; exit 1; }
export ASADMIN_CLASSPATH="$AS_INSTALL/appserver-cli.jar:${ASADMIN_CLASSPATH}"
startAsMainProcess "$@"

# Alternatively, run the following:
# exec "$JAVA" -jar "$ASADMIN_JAR" start-domain --verbose "$@"
