#!/bin/bash

function load_login_configs {
  #       When bash is invoked as an interactive login shell, or as a  non-interac-
  #       tive  shell with the --login option, it first reads and executes commands
  #       from the file /etc/profile, if that  file  exists.   After  reading  that
  #       file,  it  looks  for  ~/.bash_profile, ~/.bash_login, and ~/.profile, in
  #       that order, and reads and executes  commands  from  the  first  one  that
  #       exists  and  is  readable.

  if [ -f /etc/profile ]; then
     source /etc/profile
  fi

  if [ -f ~/.bash_profile ]; then
     source ~/.bash_profile
  else
     if [ -f ~/.bash_login ]; then
        source ~/.bash_login
     else
        if [ -f ~/.profile ]; then
           source ~/.profile
        fi
     fi
  fi
}

function load_interactive_configs {
  if [ -f ~/.bashrc ]; then
       source ~/.bashrc
  fi
}

function override_jb_variables {
  for VARIABLE in $(env)
  do
    NAME=${VARIABLE%%=*}
    if [[ $NAME = '_INTELLIJ_FORCE_SET_'* ]]
    then
      NEW_NAME=${NAME:20}
      if [ -n "$NEW_NAME" ]
      then
        VALUE=${VARIABLE#*=}
        export "$NEW_NAME"="$VALUE"
      fi
    fi
  done
}

if [ -n "$LOGIN_SHELL" ]; then
  load_login_configs
  unset LOGIN_SHELL
fi

load_interactive_configs

override_jb_variables

# mappings for Ctrl-left-arrow and Ctrl-right-arrow for word moving
bind '"\e\e[C":forward-word'
bind '"\e\e[D": backward-word'
bind '"\e\O[C":forward-word'
bind '"\e\O[D": backward-word'

function generate_command_executed_sequence() {
   printf '\e\7'
}

export -f generate_command_executed_sequence


#generate escape sequence after command is executed to notify jediterm emulator
trap "generate_command_executed_sequence" DEBUG

if [ -n "$JEDITERM_USER_RCFILE" ]
then
  source "$JEDITERM_USER_RCFILE"
  unset JEDITERM_USER_RCFILE
fi

if [ -n "$JEDITERM_SOURCE" ]
then
  source "$JEDITERM_SOURCE"
  unset JEDITERM_SOURCE
fi

function configureCommandHistory {
  local commandHistoryFile="$__INTELLIJ_COMMAND_HISTFILE__"
  if [ -n "$commandHistoryFile" ]
  then
    if ! [ -s "$commandHistoryFile" ] && [ -f "$HISTFILE" ]
    then
      command cp "$HISTFILE" "$commandHistoryFile"
    fi
    export HISTFILE="$commandHistoryFile"
  fi
}
configureCommandHistory
