#!sh
# vim: ft=sh:fdm=marker:fdl=0:noml:

[ -n "${shared_rc_loaded}" ] && return 0

[ -n "${INHERIT_ENV}" ] && return 0

# our TERM is typically tmux-256color. osx: doesnt seem to recognize it.
# export TERM=xterm
# if [ -n "${TMUX:-}" ]; then
#   export TERM=tmux-256color
# # elif [ -n "${DISPLAY:-}" ]; then
# #   export TERM=st-256color
# fi

# avoid closing shell by accident if running in a local terminal
# if [ -z "${SSH_CONNECTION}" ]; then
#   set -o ignoreeof
# fi

# no new mail warning
unset -v MAILCHECK

# osx
# if command -v -- brew >/dev/null 2>&1; then
#   # placed ahead since it modifies $path and $fpath
#   [ -z "${HOMEBREW_PREFIX-}" ] &&
#     HOMEBREW_PREFIX="$(command brew --prefix)"
#     # see: https://docs.brew.sh/Shell-Completion
#     # shellcheck disable=SC2312
#     eval "$("${HOMEBREW_PREFIX-}"'/bin/brew' shellenv)"
#     # eval "$(/opt/homebrew/bin/brew shellenv)"
# fi

if [ "${OS-}" = "darwin" ]; then
  # start the daemon here since osx doesnt have windowmanager
  gpg-agent --daemon >/dev/null 2>&1
  unset SSH_AGENT_PID
  export GPG_TTY="${TTY-}"
  if [ "${gnupg_SSH_AUTH_SOCK_by:-0}" -ne $$ ]; then
    SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
    export SSH_AUTH_SOCK
  fi
fi

# gpg cli in the tty
GPG_TTY="$(tty)"
export GPG_TTY
# export GPG_TTY="${TTY-}"

export SSH_KEY_PATH="${HOME%/}"'/.ssh/id_ed25519'

# $CDPATH
# CDPATH=.:${HOME%/}/.config
# CDPATH=..
# CDPATH=$HOME:..
# export CDPATH
export CDPATH="${CDPATH:+${CDPATH-}:}${HOME%/}"

# general shell settings
export FIGNORE='~:.o:.swp:.DS_Store:.svn'

# HISTSIZE | POSIX min. 128
# export HISTSIZE=
# see: https://github.com/Homebrew/brew/pull/21157#issue-3683228299
active_shell="$(sh -c 'command -p -- lsof -p "$PPID" -a -d cwd -Fc | /usr/bin/sed -n "s/^c//p"')"
# shellcheck disable=SC2155
# export HISTFILE="${XDG_STATE_HOME-}/$(basename -- "${0#-*}")_history"
export HISTFILE="${XDG_STATE_HOME-}/${active_shell}_history"

# do not add root commands to history
# shellcheck disable=SC2312
if [ "$('command' 'id' '-u')" = 0 ]; then
  unset HISTFILE
  export SAVEHIST=0
fi

# POSIX.1-2024 2.5.3 Shell Variables
# PS1='$ '
# PS2='> '
# PS4='+ '

# . "${XDG_CONFIG_HOME-}"/shell/aliases
. "${XDG_CONFIG_HOME-}"/shell/prompt.sh

# prompt() {
#   # h="$(uname -n | cut -c-1)"
#   # d="$(echo "${PWD}" | sed -e "s|^${HOME}|~|" -e 's-\([^/.]\)[^/]*/-\1/-g')"
#   # shellcheck disable=SC2312
#   printf '%s %s' "$(uname -n | cut -c-1)" "$(echo "${PWD}" | sed -e "s|^${HOME}|~|" -e 's-\([^/.]\)[^/]*/-\1/-g')"
# }

# PS1='$(prompt) \$ '
PS1='$(_ps1) \$ '

# . "$XDG_CONFIG_HOME"/profile.d/25-PATH.sh
# shellcheck source=.pathrc
# . "${HOME%/}"'/.pathrc'

# manpath/infopath {{{

# subdirectories of other manpaths must be mentioned before the containing manpath.
# e.g. /usr/man/preformat must be listed before /usr/man.
# /usr/share/man/newOS:/usr/share/man:/usr/local/man/newOS:/usr/local/man
# setenv MANPATH "/usr/share/man:/usr/local/share/man:/usr/local/*/share/man:/opt/homebrew/share/man:/Users/user/.local/share/man":
test -d '/usr/share/man' &&
  MANPATH='/usr/share/man'"${MANPATH:+:${MANPATH-}}"
test -d '/usr/local/man' &&
  MANPATH='/usr/local/man'"${MANPATH:+:${MANPATH-}}"
test -d '/usr/local/share/man' &&
  MANPATH='/usr/local/share/man'"${MANPATH:+:${MANPATH-}}"
test -d "${HOME%/}"'/.local/man' &&
  MANPATH="${HOME%/}"'/.local/man'"${MANPATH:+:${MANPATH-}}"
test -d "${HOME%/}"'/.local/share/man' &&
  MANPATH="${HOME%/}"'/.local/share/man'"${MANPATH:+:${MANPATH-}}"
test -d '/opt/homebrew/share/man' &&
  MANPATH='/opt/homebrew/share/man'"${MANPATH:+:${MANPATH-}}"
command man -w >/dev/null 2>&1 &&
  MANPATH="${MANPATH:+${MANPATH-}:}$(command man -w)"

# infopath
test -d '/usr/share/info' &&
  INFOPATH='/usr/share/info'"${INFOPATH:+:${INFOPATH-}}"
test -d '/usr/local/share/info' &&
  INFOPATH='/usr/local/share/info'"${INFOPATH:+:${INFOPATH-}}"
test -d '/opt/homebrew/share/info' &&
  INFOPATH='/opt/homebrew/share/info'"${INFOPATH:+:${INFOPATH-}}"
export INFOPATH

# }}}

# direnv {{{

# shellcheck disable=SC2312
if command -v direnv >/dev/null 2>&1; then
  case "${active_shell-}" in
    zsh)
      eval "$(direnv hook zsh)" ;;
    bash)
      eval "$(direnv hook bash)" ;;
    *)
      return ;;
  esac

  show_virtual_env() {
    if [ -n "${VIRTUAL_ENV}" ] && [ -n "${DIRENV_DIR}" ]; then
      echo "($(basename "${VIRTUAL_ENV}"))"
    fi
  }
  # export -f show_virtual_env
  # shellcheck disable=SC2250
  PS1='$(show_virtual_env)'$PS1
fi

# }}}

# shellfish {{{

if [ "${OS-}" = "linux" ]; then
  # shellcheck source=/dev/null
  test -e "${HOME%/}"'/.shellfishrc' && . "${HOME%/}"'/.shellfishrc'
  alias shellfishreload='LC_TERMINAL=ShellFish . "${HOME%/}"'\''/.shellfishrc'\'''
fi

# }}}

# set the active shell as the detectected POSIX (.sh) shell
# do not export
if test -n "${BASH_VERSION:-}"; then
  ACTIVE_POSIX_SHELL='bash'
elif test -n "${ZSH_VERSION:-}"; then
  ACTIVE_POSIX_SHELL='zsh'
elif test "$0" = '-dash' -o "$0" = 'dash'; then
  # dash does not define DASH_VERSION
  ACTIVE_POSIX_SHELL='dash'
elif test -n "${KSH_VERSION:-}"; then
  ACTIVE_POSIX_SHELL='ksh'
else
  ACTIVE_POSIX_SHELL='sh'
fi

case ${ACTIVE_POSIX_SHELL} in
  bash|dash|sh)
    # shellcheck source=.config/shell/alias.sh
    . "${XDG_CONFIG_HOME-}"'/shell/alias.sh'
    # shellcheck source=.config/shell/darwin.sh
    . "${XDG_CONFIG_HOME-}"'/shell/'"${OS-}"'.sh'
    # shellcheck source=.config/shell/function.sh
    . "${XDG_CONFIG_HOME-}"'/shell/function.sh'
    # shellcheck source=.config/shell/lib.sh
    . "${XDG_CONFIG_HOME-}"'/shell/lib.sh'
    # shellcheck source=.config/shell/libgit.sh
    . "${XDG_CONFIG_HOME-}"'/shell/libgit.sh'
# if [ -n "${shell_interactive}" ] && [ "${TERM-}" != 'dumb' ]; then
#   if command -v fzf >/dev/null 2>&1; then
#     # shellcheck source=.config/shell/fzf.sh
#     . "${XDG_CONFIG_HOME-}"'/shell/fzf.sh'

#     # shellcheck source=.config/shell/libfzf.sh
#     . "${XDG_CONFIG_HOME-}"'/shell/libfzf.sh'
#   fi
# fi
    ;;
  *)
    return
    ;;
esac

# for file in "${HOME%/}"/.config/shell/*sh; do
#   . "${file-}"
# done
# unset -v -- file

# SESSION_START="$(date -Iseconds)"
# export SESSION_START

sh << 'EOF' # permanent history entries
    HISTFILE="${HISTFILE:-$HOME/.sh_history}"
    touch "$HISTFILE"

    perm="$(mktemp)" || exit $?
    trap 'rm "$perm"' EXIT

    IFS=:
    for file in ${SH_HIST_SAV:-"$XDG_CONFIG_HOME"/shell/history.sav}; do
        [ -s "$file" ] && cat "$file" >> "$perm";
    done
    [ ! -s "$perm" ] && exit

    temp="$(mktemp)" || exit $?
    grep -v -F -x -f "$HISTFILE" "$perm" | cat - "$HISTFILE" > "$temp"

    if [ "$(wc -l < "$temp")" -gt "$(wc -l < "$HISTFILE")" ]; then
        mv "$temp" "$HISTFILE"
    else
        rm "$temp"
    fi
EOF

# shellcheck disable=SC1090,SC2154
# trap '
#     lg="$XDG_CONFIG_HOME"/shell/logout
#     [ -f "$lg" ] && . "$lg"
# ' EXIT

# [ -f "${XDG_STATE_HOME-}/OLDPWD" ] && . "${XDG_STATE_HOME}/OLDPWD"

# private
# command touch -- "${HOME%/}"'/.env' &&
#   command chmod -- 400 "${HOME%/}"'/.env' &&
#   . "${HOME%/}"'/.env'

shared_rc_loaded=y
