#!/bin/sh

# echo Loading shell environment ... >&2

# # Convenience functions for running Emacs in various ways.
# em() {
#   if [ "$#" -eq 0 ]; then
#     echo "Starting new Emacs process ..." >&2
#     emacs &
#     disown
#   elif emacsclient -n "$@" 2>/dev/null; then
#     echo "Opened $@ in Emacs server" >&2
#   else
#     echo "Opening $@ in a new Emacs process ..." >&2
#     emacs "$@" &
#     disown
#   fi
# }
#
# [ -e ~/.remote ] && alias em=emacs
#
# emc() {
#   emacsclient "$@"
# }
#
# emt() {
#   emacs -nw "$@"
# }

# set my Git user details locally in the current repository.
gitme() {
  git config user.name "Susam Pal"
  git config user.email susam@susam.net
  git config user.name
  git config user.email
}

# Show the current effective Git user.
gitwho() {
  git config user.name
  git config user.email
}

# clone GitHub repository.
ghclone() {
  cd ~/git || return
  pwd
  if [ $# -eq 1 ]; then
    git clone "https://github.com/susam/$1.git"
    cd "$1" || return
  else
    git clone "https://github.com/$1/$2.git"
    cd "$2" || return
  fi
  pwd
}

# go to the top-level directory of the current project.
gcd() {
  check_path=$PWD
  while [ "$check_path" != / ]; do
    [ -d "$check_path/.git" ] && cd "$check_path" && break
    check_path=${check_path%/*}
  done
}

# OCR PDFs.
ocr() {
  for f in "$@"; do
    echo "OCRing $f ..."
    ocrmypdf --force-ocr "$f" "${f%.pdf}-ocr.pdf"
    mv "$f" "$f.bkp"
    mv "${f%.pdf}-ocr.pdf" "$f"
    ls -lh "$f.bkp"
    ls -lh "$f"
  done
}

# Clean environment.
dirclean() {
  find . -name "__pycache__" -exec rm -v -r {} +
  find . -name "*.pyc" -exec rm -v {} +
  find . -name ".DS_Store" -exec rm -v {} +
}

# Search texlive for file
findtl() {
  find /usr/local/texlive -name "*$1*"
}

grepx() {
  grep -r -I --exclude-dir=".[^/]*" --exclude-dir=venv/ --exclude-dir=node_modules/ "$@"
}

findx() {
  find . | grep -vE "/\.|__pycache__" | grep "$1"
}

# Apple documentation for keyboard usage IDs:
# https://developer.apple.com/library/archive/technotes/tn2450/_index.html

# Remap keys in Mac British keyboard to US layout keys.
mbk() {
  # section/plus-minus (0x64) -> backquote/tilde (0x35)
  # return (0x28) -> \| (0x31)
  # \| (0x31) -> return (0x28)
  # non-us ~# (0x32) (absent) -> return (0x28) (transition)
  hidutil property --set '{"UserKeyMapping": [
      {
        "HIDKeyboardModifierMappingSrc": 0x700000064,
        "HIDKeyboardModifierMappingDst": 0x700000035
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x700000028,
        "HIDKeyboardModifierMappingDst": 0x700000031
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x700000031,
        "HIDKeyboardModifierMappingDst": 0x700000028
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x700000032,
        "HIDKeyboardModifierMappingDst": 0x700000028
      }
    ]}'
}

# Remap keys in external British keyboard to Macbook US layout keys.
ebk() {
  # return (0x28) -> non-us ~# (but types \|) (0x32)
  # \| (0x31) (absent) -> return (0x28) (transition)
  # non-us ~# (0x32) (but types \|) -> return (0x28)
  # left alt (0xe2) -> left gui (0xe3)
  # left gui (0xe3) -> left alt (0xe2)
  hidutil property --set '{"UserKeyMapping": [
      {
        "HIDKeyboardModifierMappingSrc": 0x700000028,
        "HIDKeyboardModifierMappingDst": 0x700000032
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x700000031,
        "HIDKeyboardModifierMappingDst": 0x700000028
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x700000032,
        "HIDKeyboardModifierMappingDst": 0x700000028
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x7000000e2,
        "HIDKeyboardModifierMappingDst": 0x7000000e3
      },
      {
        "HIDKeyboardModifierMappingSrc": 0x7000000e3,
        "HIDKeyboardModifierMappingDst": 0x7000000e2
      }
    ]}'
}

nok() {
  hidutil property --set '{"UserKeyMapping": []}'
}

# # Set environment.
# PATH=~/bin:$PATH
# PATH=$PATH:/usr/local/smlnj/bin
# if command -v opam >/dev/null; then
#   eval $(opam env)
# fi
#
# _begin_esc() {
#   [ -n "$BASH_VERSION" ] && printf '\x01' && return
#   [ -n "$ZSH_VERSION" ] && printf '%%{' && return
# }
#
# _end_esc() {
#   [ -n "$BASH_VERSION" ] && printf '\x02' && return
#   [ -n "$ZSH_VERSION" ] && printf '%%}' && return
# }

# Set terminal color.
_tput_color() {
  _begin_esc
  tput setaf "$1"
  _end_esc
}

# Reset terminal color.
_tput_reset() {
  _begin_esc
  tput sgr0
  _end_esc
}

# Color palette.
# if [ -n "${INSIDE_EMACS-}" ]; then
#   YELLOW=226
#   CYAN=87
#   GREEN=40
#   ORANGE=208
# else
#   YELLOW=11
#   CYAN=14
#   GREEN=2
#   ORANGE=208
# fi
#
# Create dynamic prompt string for PS1.
# _active_prompt() {
#   # Git branch
#   git_branch=$(git branch 2>/dev/null | sed -n "s/^\* *//p")
#   if [ -n "$git_branch" ]; then
#     _tput_color "$YELLOW"
#     printf '[%s] ' "$git_branch"
#   fi
#   unset git_branch
#
#   # Current session
#   if [ -f ~/.remote ]; then
#     _tput_color "$CYAN"
#     printf "$(id -un)@$(hostname) "
#   fi
#
#   # Current directory
#   if [ "$PWD" != "$HOME" ]; then
#     if printf '%s' "$PWD" | grep -q "^$HOME"; then
#       neat_path="~${PWD#$HOME}"
#     else
#       neat_path=$PWD
#     fi
#     _tput_color "$GREEN"
#     printf '%s' "$neat_path"
#     unset neat_path
#   fi
#
#   # Dollar or beer sign
#   _tput_color "$ORANGE"
#   if [ -n "$_PROMPT_MARK" ]; then
#     printf '%s' "$_PROMPT_MARK"
#   elif date +"%a" | grep -qE 'Fri|Sat|Sun'; then
#     printf '%s' "$_books "
#   else
#     printf '$ '
#   fi
#   _tput_reset
# }

# Aliases to modify the ending characters of the primary prompt.
_beer=$(printf "\xf0\x9f\x8d\xba")
_books=$(printf "\xf0\x9f\x93\x9a")
alias dollar='_PROMPT_MARK="$ "'
alias beer='_PROMPT_MARK="$_beer "'
alias books='_PROMPT_MARK="$_books "'

# Aliases for Timeboxing.
alias tm='timebox'
alias tmt='grep "$(date +"%Y-%m-%d")" ~/timebox.log'
alias tml='tmt; echo [ $(tmt | wc -l) ]'
alias tmla='cat ~/timebox.log'
alias tmc='cut -d" " -f1 ~/timebox.log | uniq -c'
# shellcheck disable=SC2154
alias tmu='sed \$d ~/timebox.log > ~/t.new && mv ~/t.new ~/timebox.log && tml'
alias tmr=': > ~/timebox.log'

# Aliases for Common Lisp.
alias cl='sbcl --noinform --quit --load'

alias c++11="c++ -g -std=c++11 -Wall -Wextra -pedantic"

# Set the primary prompt string.
PS1='$(_active_prompt)'

# For specific shells only.
if [ -n "$BASH_VERSION" ]; then
  echo Loading Bash environment ... >&2

  [ -r "/usr/local/etc/profile.d/bash_completion.sh" ] \
    && . "/usr/local/etc/profile.d/bash_completion.sh"
elif [ -n "$ZSH_VERSION" ]; then
  echo Loading ZSH environment ... >&2

  setopt prompt_subst
  autoload bashcompinit && bashcompinit
  autoload compinit && compinit
fi

# [ -f ~/my/bin/shrc ] && . ~/my/bin/shrc
# [ -f ~/ws/bin/shrc ] && . ~/ws/bin/shrc
# [ -f ~/.cargo/env ] && . ~/.cargo/env

# Attach to an existing Screen session or launch a new one.
# [ -n "$STY$TMUX" ] || screen -dRR

# Attach to an existing tmux or a launch new tmux.
# [ -n "$STY$TMUX$INSIDE_EMACS" ] || tmux at || tmux

# echo Done >&2
