# shellcheck shell=bash
# Copyright (c) 2023 Termius Corporation.

# Inspired by implementation in Visual Studio Code
# ---------------------------------------------------------------------------------------------
#   Copyright (c) Microsoft Corporation. All rights reserved.
#   Licensed under the MIT License.
# ---------------------------------------------------------------------------------------------

builtin autoload -Uz add-zsh-hook

if [[ -n "$_termius_integration_installed" ]]; then
  ZDOTDIR=$ORIGINAL_ZDOTDIR
  builtin return
fi

# By default, zsh will set the $HISTFILE to the $ZDOTDIR location automatically. In the case of the
# shell integration being injected, this means that the terminal will use a different history file
# to other terminals. To fix this issue, set $HISTFILE back to the default location before ~/.zshrc
# is called as that may depend upon the value.
HISTFILE=$ORIGINAL_ZDOTDIR/.zsh_history

# shellcheck disable=SC2154 # Options are built-in table in ZSH
if [[ ${options[norcs]} = off && -f "$ORIGINAL_ZDOTDIR/.zshrc" && "$ORIGINAL_ZDOTDIR" != "$ZDOTDIR" ]]; then
  # Set original ZDOTDIR when sourcing the user's .zshrc
  _termius_zdotdir=$ZDOTDIR
  ZDOTDIR=$ORIGINAL_ZDOTDIR
  # shellcheck disable=SC1091 # don't check user's configuration
  . "$ORIGINAL_ZDOTDIR/.zshrc"
  ZDOTDIR=$_termius_zdotdir
fi

function _termius_encode() {
  builtin echo -n "$1" | command base64
}

function _termius_set_cwd {
  builtin printf '\e]4545;P;Cwd=%s\a' "$(_termius_encode "${PWD}")"
}

add-zsh-hook precmd _termius_set_cwd

if [[ ${options[login]} = off ]]; then
  # .zshrc is the last startup file if shell is non-login.
  # Restore original ZDOTDIR
  ZDOTDIR=$ORIGINAL_ZDOTDIR
fi

_termius_integration_installed="yes"
