#!/bin/bash

set -e

function get_script_location()    # https://stackoverflow.com/a/246128
{
    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
      DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
      # Note symlinks will fail on macOS due to missing readlink command
      SOURCE="$(readlink "$SOURCE")"
      [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
    done
    DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
    echo $DIR
}

DIR=$(get_script_location)

if [[ -t 0 || -p /dev/stdin ]]; then    # http://tldp.org/LDP/abs/html/intandnonint.html
    TTY=$(tty || true)
else
    unset TTY
fi
if [[ "$TTY" = "not a tty" ]]; then    # work around old versions of Docker
  unset TTY
fi

echo "${0##*/} $$ running"

if hash setsid 2>/dev/null; then
    # creates a new process group (and a new session)
    # to see process groups (PGID's), try 'pstree -g' or something like:
    #     ps -u yourname -o pid,ppid,pgid,args | head -1 ; ps -u yourname -o pid,ppid,pgid,args | grep -E 'omnisci|calcite' | grep -v grep
    if [ "$TTY" != "" ]; then
      setsid $DIR/scripts/innerstartheavy "$@" <$TTY &
    else
      setsid $DIR/scripts/innerstartheavy --non-interactive "$@" &
    fi
    SUBPID=$!
else
    # setsid missing on macOS
    # this should still work but not quite as cleanly as with setsid
    PGID=$$
    export PGID
    if [ "$TTY" != "" ]; then
      $DIR/scripts/innerstartheavy "$@" <$TTY &
    else
      $DIR/scripts/innerstartheavy --non-interactive "$@" &
    fi
    SUBPID=$!
fi

# Immediately kill the single $SUBPID process if this script gets a signal.
# This script will also exit due to the wait on the last line unblocking and/or
# because bash will always stop this script if a CTRL-C is typed.
trap 'set +e ; trap - SIGTERM ; echo ; echo "${0##*/} $$ shutting down" ; kill $SUBPID 2>/dev/null' SIGHUP SIGINT SIGTERM

# To be safe kill the entire $SUBPID process group when this script exits for any reason.
# This happens after a short delay to give OmniSciDB C++ a chance to shut itself down cleanly
# if an earlier signal+trap triggered this exit.
trap 'set +e ; trap - SIGTERM ; sleep 1 ; kill -- -$SUBPID 2>/dev/null ; sleep 1 ; echo "${0##*/} $$ exited"' EXIT

# Be aware that CTRL-C has special handling by bash. Pressing
# CTRL-C at the terminal causes Bash to send SIGINT to the entire
# process group before this trap gets run. Bash also kills this
# script after CTRL-C after the trap runs even if we wanted this
# script to keep running.

wait $SUBPID
