#!/bin/bash
#
# Copyright (c) 2023, 2025 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" -jar "$ASADMIN_JAR" 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 read 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" -jar "$ASADMIN_JAR" start-domain --dry-run "$@" || echo "FAILED" )
    if [[ x"$DRY_RUN_OUTPUT" == x ]]
      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})
    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; }

ASADMIN_JAR="$AS_INSTALL/modules/admin-cli.jar"
startAsMainProcess "$@"

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