#!/bin/bash

set -e
PID=$$
PGID=${PGID:=$PID}

# Kills all child processes in this script's same process group
# if a signal happens or if this script exits for any reason.
trap 'set +e ; trap "" SIGTERM ; kill -- -$PGID ; trap - SIGHUP SIGINT SIGTERM EXIT ; exit' SIGHUP SIGINT SIGTERM EXIT

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)
DIR="$DIR/.."

MAPD_TCP_PORT=${MAPD_TCP_PORT:=6274}
MAPD_HTTP_PORT=${MAPD_HTTP_PORT:=6278}
MAPD_WEB_PORT=${MAPD_WEB_PORT:=6273}
MAPD_CALCITE_PORT=${MAPD_CALCITE_PORT:=6279}

MAPD_DATA=${MAPD_DATA:="storage"}

while (( $# )); do
    case "$1" in
        --read-only)
            RO="--read-only" ;;
        --base-port)
            shift
            MAPD_WEB_PORT=$1
            MAPD_TCP_PORT=$(($MAPD_WEB_PORT-1))
            MAPD_HTTP_PORT=$(($MAPD_WEB_PORT-2))
            MAPD_CALCITE_PORT=$(($MAPD_WEB_PORT+1))
            ;;
        --data)
            shift
            MAPD_DATA=$1
            ;;
        --enable-https)
            HTTPS="--enable-https" ;;
        --cert)
            shift
            HTTPS_CERT="--cert $1" ;;
        --key)
            shift
            HTTPS_KEY="--key $1" ;;
        --config)
            shift
            if [ -e "$1" ]; then
                CONFIG_FILE="$1"
                CONFIG="--config $1"
            else
                echo "WARN: config file does not exist, ignoring: --config $1" >&2
            fi
            ;;
        --non-interactive)
            INSERT_SAMPLE_DATA=false ;;
        --disable-open-frontend)
            DISABLE_OPEN_FRONTEND=true ;;
        --sample-data)
            INSERT_SAMPLE_DATA=true ;;
        --verbose)
            VERBOSE="--verbose" ;;
        *)
            break ;;
    esac
    shift
done

echo "Backend TCP:  localhost:${MAPD_TCP_PORT}"
echo "Backend HTTP: localhost:${MAPD_HTTP_PORT}"
echo "Frontend Web: localhost:${MAPD_WEB_PORT}"
echo "Calcite TCP:  localhost:${MAPD_CALCITE_PORT}"

if [ ! -d $MAPD_DATA ]; then
    mkdir -p $MAPD_DATA
    ./bin/initheavy -f --data $MAPD_DATA
fi

# Rename the log directory, if it exists, so that the web server can start out writing to the correct directory.
if [[ -d $MAPD_DATA/mapd_log && ! -L $MAPD_DATA/mapd_log ]]; then
  mv $MAPD_DATA/mapd_log $MAPD_DATA/log
  ln -sfn log $(readlink -f $MAPD_DATA)/mapd_log
  echo "Rebrand migration: Added symlink from $(readlink -f $MAPD_DATA)/mapd_log to log"
fi

VMAJOR=${BASH_VERSINFO[0]}
VMINOR=${BASH_VERSINFO[1]}
if [[ $VMAJOR -eq 4 && $VMINOR -le 3 || $VMAJOR -lt 4 ]]; then    # Bash 4.3 and older (CentOS)
    LEGACY=1
else
    unset LEGACY
fi

MACHINE_ARCH=$(uname -m)
for i in "/etc/xdg" "/etc" "/usr/local/share" "/usr/share"; do
  if [ -f "$i/vulkan/icd.d/nvidia_icd.json" ]; then
    icd_path="$i/vulkan/icd.d/nvidia_icd.json"
    break
  elif [ -f $i/vulkan/icd.d/nvidia_icd.$MACHINE_ARCH.json ]; then
    icd_path=$i/vulkan/icd.d/nvidia_icd.$MACHINE_ARCH.json
    break
  fi
done

if [[ -z "$icd_path" ]]; then
  YELLOW='\033[1;33m'
  NORMAL='\033[0m'
  LBLUE='\033[1;34m'
  echo -e "${YELLOW}Warning: ${NORMAL}Cannot find the Nvidia Vulkan driver manifest file \"nvidia_icd.json\" in the expected system directories. As a result the backend renderer may not work.
  Please verify that the nvidia driver and vulkan loader are installed appropriately.
  See: ${LBLUE}https://docs.omnisci.com/troubleshooting/vulkan-graphics-api-beta#bare-metal-installs${NORMAL} for some installation and troubleshooting tips."
else
    export VK_ICD_FILENAMES=$icd_path
fi

./bin/heavydb $MAPD_DATA $RO --port $MAPD_TCP_PORT --http-port $MAPD_HTTP_PORT --calcite-port $MAPD_CALCITE_PORT $CONFIG $VERBOSE $* &
PID1=$!
echo "- heavydb $PID1 started"

if [ "$INSERT_SAMPLE_DATA" = true ]; then
    echo "- waiting 5s before inserting sample data"
    sleep 5
    . "$DIR/insert_sample_data"
fi

if [ -d frontend ] && [ -e ./bin/heavy_web_server ]; then
    # use https for backend-url if both ssl-cert and ssl-key options are in the config file
    BACKEND_URL="--backend-url http://localhost:${MAPD_HTTP_PORT}"
    if [ -e "$CONFIG_FILE" ]; then
        if grep --quiet "^ssl-cert" "$CONFIG_FILE" && grep --quiet "^ssl-private-key" "$CONFIG_FILE"; then
            BACKEND_URL="--backend-url https://localhost:${MAPD_HTTP_PORT}"
        fi
        # always use backend-url from the config file
        if grep --quiet "^backend-url" "$CONFIG_FILE"; then
            BACKEND_URL=""
        fi
    fi
    ./bin/heavy_web_server $RO --port $MAPD_WEB_PORT ${BACKEND_URL} --data $MAPD_DATA $HTTPS $HTTPS_CERT $HTTPS_KEY $CONFIG $VERBOSE &
    PID2=$!
    echo "- heavy_web_server $PID2 started"

    if [ ! "$DISABLE_OPEN_FRONTEND" = true ]; then
        if [ ! -z "$HTTPS" ] ; then
            MAPDFRONTEND="https://localhost:${MAPD_WEB_PORT}"
        else
            MAPDFRONTEND="http://localhost:${MAPD_WEB_PORT}"
        fi
        sleep 5
        if hash open 2>/dev/null; then
            open "$MAPDFRONTEND" 2> /dev/null || true
        elif hash xdg-open 2>/dev/null; then
            xdg-open "$MAPDFRONTEND" 2> /dev/null || true
        else
            echo "Navigate to: $MAPDFRONTEND"
        fi
    else
        echo "Navigate to: $MAPDFRONTEND"
    fi
fi

if [ "$LEGACY" = "" ]; then
  wait -n
else
  wait $PID1
fi
